What link do I call to Amazon s3 when I use axios - reactjs

I'm new to S3 so I didn't find anywhere in the API where it says that this is the respective URL to use for the axios URL parameter. I'm keeping on getting a 404 error saying that the
axios({
url: `call/s3/backend`,
method: "post",
data: {
//images: imageArray.toByteArray(),
},
})
.then((res) => {
//imageUrlArr = res.data;
axios({
url: `api/petition_posts`,
method: "post",
data: {
petition_post: {
title: title,
description: description,
hashtags: arrayOfHashtags.join(" "),
amount_donated: 0,
//media: imageUrlArr,
goal: money,
card_type: "petition",
org_profile_id: 1,
},
},
})
.then((res) => {
console.log(res.data);
})
.catch((error) => console.log(error));
})
.catch((error) => console.log(error));
}
titleError(true ? title.length === 0 : false);
descriptionError(true ? description.length === 0 : false);
};

To upload a file from the browser to S3 using Axios:
fetch a pre-signed S3 URL from your server
PUT the file to the pre-signed URL using Axios
Server:
const aws = require('aws-sdk')
aws.config.update({
accessKeyId: '...',
secretAccessKey: '...'
})
const s3 = new aws.S3()
const params = {
Bucket: 'my-bucket',
Key: 'my-file.txt',
Expires: 300,
ContentType: 'text/plain'
}
s3.getSignedUrl('putObject', params,
(error, signedUrl) => return signedUrl /* to client */ )
Client:
const axios = require('axios')
axios.put(<signed-url-from-server>, 'abc', {
headers: {
'Content-Type': 'text/plain'
}
}).then(res => console.info(res))
.catch(err => console.error(err))

Related

Preflight response is not successful. Status code: 403. React, Flask and Stripe?

I feel like I've looked everywhere for this and can't find my answer!
I've got a React app working with a Node server, but I need to get it to work with a Flask server instead.
This is my React code:
function buy() {
window.scroll(0, 0);
fetch(`${IP}/init_checkout`, {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
body: JSON.stringify({
price_id: 'my_stripe_product_price',
}),
})
.then(res => {
if (res.ok)
return res.json();
return res.json().then(json => Promise.reject(json));
})
.then(({ url }) => {
window.location = url;
})
.catch(e => {
console.error(e.error);
});
}
And, my route in Flask:
#app.route('/init_checkout', methods=['POST'])
#cross_origin(origin="*")
def init_checkout():
data = json.loads(request.data)
price_id = data['price_id']
try:
checkout_session = stripe.checkout.Session.create(
success_url='http://localhost:3000', # noqa
cancel_url='http://localhost:3000/form',
payment_method_types=[
'card', 'sepa_debit', 'sofort', 'ideal'
],
mode='subscription',
line_items=[{
'price': price_id,
'quantity': 1
}],
)
return redirect(checkout_session.url, code=303)
except Exception as e:
print(str(e))
return jsonify({'error': {'message': str(e)}}), 400
In the console, I get the url I'd like to get too, but the app won't automatically direct me there?
Just for reference in case anyone else comes across this or similar ... thanks to hmunoz:
function buy() {
window.scroll(0, 0);
fetch(`${IP}/init_checkout`, {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
body: JSON.stringify({
price_id: 'my_stripe_product_price',
}),
})
.then(res => {
if (res.ok)
return res.json();
return res.json().then(json => Promise.reject(json));
})
.then(({ url }) => {
window.location = url;
})
.catch(e => {
console.error(e.error);
});
}
And, my route in Flask:
#app.route('/init_checkout', methods=['POST'])
#cross_origin(origin="*")
def init_checkout():
data = json.loads(request.data)
price_id = data['price_id']
try:
checkout_session = stripe.checkout.Session.create(
success_url='http://localhost:3000', # noqa
cancel_url='http://localhost:3000/form',
payment_method_types=[
'card', 'sepa_debit', 'sofort', 'ideal'
],
mode='subscription',
line_items=[{
'price': price_id,
'quantity': 1
}],
)
return checkout_session
except Exception as e:
print(str(e))
return jsonify({'error': {'message': str(e)}}), 400

How to send a image jpg/png file from react to express server

I am trying to send an object from react to express server using node.js
this is my object:
const formData = {
location: location,
cost: cost,
email: email,
image: image,
};
This is my fetch post method :
fetch("http://localhost:5000/places", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(formData),
})
.then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
I can see the image file object in client site console but I am not getting that in expreess server.
You have to send your input data as FormData to share images/files to the backend.
function uploadImage() {
let formData = new FormData(yourFormData);
fetch("http://localhost:5000/places", {
method: "POST",
body: formData,
}).then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
}

Is it possible to use API Routes as Proxy to my existing RoR Backend

Every time NextJs request for an api, it will come first to api routes before it redirected to my RoR backend service.
I use this to encrypt my access token to session NextJS using iron-session once I get the data from backend.
## src/pages/api/login.ts
const loginRoute = async (req: NextApiRequest, res: NextApiResponse) => {
const response = await fetch(`backend-service/authorizations.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: req.body.username,
password: req.body.password
})
})
.then((res) => {
if (!res.ok) {
return res.text().then((text) => {
throw new Error(text)
})
}
return res
})
.then((res) => res.json())
.catch((err) => {
res.status(401).json({ message: err })
})
if (response) {
req.session.user = response
await req.session.save()
res.json(response)
}
}
export default withSessionRoute(loginRoute)
Is this a valid use case for API Routes in NextJS?
Thanks in advance!

react native upload image with axios

I have this data
came from react-native-image-picker
data: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Qtan" => 90kb
fileName: "77677.jpg"
fileSize: 67542
height: 600
isVertical: true
originalRotation: 0
path: "/storage/emulated/0/Download/77677.jpg"
type: "image/jpeg"
uri: "content://media/external/images/media/18584"
width: 399
__proto__: Object
and am try to set this data in object type #FromData to upload #img
var binaryDataInBase64 = new FormData();
binaryDataInBase64.append('file', {
// data: response.data,
uri: 'file://' + response.uri,
name: 'MMM.jpg',
type: response.type
})
console.log('=======================>', binaryDataInBase64)
axios.post(
'https://danskeclouddemo.com/api/file',
{ file: binaryDataInBase64 },
{ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data' } }
).then(res => {
console.log(res)
}).catch(error => {
console.log(error)
})
and this is BackEnd Postman Working good Postman collection
//======================
//======================
Edit
Some people talk about the problem from react native version after 0.61.5
in this link issues
Your form data must be like that.
formdata.append('file',{
uri: Platform.OS === 'android' ? photo.uri : 'file://' + photo.uri,
name: 'test',
type: 'image/jpeg' // or your mime type what you want
});
Then
axios.post('/users/profilepic', formdata, config).then((res) => {
console.log(res.data);
return res.data;
});
Rather using, axiom use fetch simple, approach to upload, image
this.setState({imageLoading:true})
const credentials={
userId:this.state.userId
}
try {
let response = await fetch(
'url',
{
'method': 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: createFormData(source, credentials)
}
);
if (response.status == 200) {
response.json().then(data => {
switch (data.status) {
case 200:
break;
}
});
}else {
this.setState({imageLoading:false ,isLoading:false})
}
} catch (error) {
this.setState({imageLoading:false,isLoading:false})
console.error(error);
}
const createFormData=(image,body)=>{
var data = new FormData();
data.append(image, {
uri: Platform.OS === "android" ? image.uri : image.uri.replace("file://", ""),
name: `dummy${Date.now()}.jpg`,
type: 'image/*'
})
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return data
}

react native post form data with object and file in it using axios

so i want to upload
object as data
and file as Note
to api using axios
uploadToServer= () => {
const file =this.state.photo
let data2 ={sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')
data.append('data[description]', "test")
data.append('data[note_content_item]', "test")
console.log(data)
axios({
url: api',
method: 'POST',
data: data,
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(resp => console.log(resp.data.response))
.catch(error => console.error(error));
}
first i am trying with data without Note i can do it in postman
but with my code i got error
message: "Can not save file"
response_code: 10
i got this error only if i change the key from data to something else
when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.
second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.
import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;
const axiosInstance = axios.create({
baseURL: 'example.com', // use with scheme
timeout: 30000,
headers: {
"X-Platform": 'iOS',
"X-App-Build-Number": '1.0.0',
},
});
const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
uri: "/dev/sda/abc.png",
type: "image/png",
name: "abc.png",
});
const config: AxiosRequestConfig = {
method: "post",
url: "/process/start",
responseType: "json",
headers: {
'Content-Type': 'multipart/form-data',
// if backend supports u can use gzip request encoding
// "Content-Encoding": "gzip",
},
transformRequest: (data, headers) => {
// !!! override data to return formData
// since axios converts that to string
return formData;
},
onUploadProgress: (progressEvent) => {
// use upload data, since it's an upload progress
// iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
},
data: formData,
};
// send post request and get response
const response = await axiosInstance.request(config);
You are not building FormData correctly, Try this:
let data = {sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
uri: "file://" //Your Image File Path
type: 'image/jpeg',
name: "imagename.jpg",
});
axios({
url : api,
method : 'POST',
data : formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(function (response) {
console.log("response :", response);
})
.catch(function (error) {
console.log("error from image :");
})
This might help you:
import {Platform} from 'react-native';
import axios from 'axios';
const upload = async readPath => {
console.log('path', readPath);
const URL = 'your-url';
const headers = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
Authorization: `Bearer ${projectSecret}`,
},
};
const formData = new FormData();
const file = {
uri:
Platform.OS === 'android' ? `file:///${readPath}` : readPath,
type: 'text/plain',
name: name,
};
formData.append('file', file);
await axios
.post(URL, formData, headers, {
timeout: 3000,
})
.then(async response => {
console.log(response.data);
})
.catch(error => {
console.log('error : ', error);
});
};

Resources