Making an axios POST request with multipart/form-data, via React Native Debugger - multipartform-data

I am trying to upload a file from React Native to my server. However I am unable to set the 'Content-Type' header to multipart/form-data.
Here's my simple request:
axios({
uri: 'http://localhost:3000',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
});
I am using the React Native Debugger to monitor Network requests.
When I see my Network request inside the Debugger, I see this:
'Content-Type': 'text/plain;charset=UTF-8'
and the Request Payload is simply [object Object]
User Agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) ReactNativeDebugger/0.7.13 Chrome/58.0.3029.110 Electron/1.7.9 Safari/537.36
If I am unable to do this with the React Native Debugger, can anyone suggest any steps to testing via Expo.

Using the latest version of Axios (0.17.1), you make an HTTP request with 'Content-Type': 'multipart/form-data' in the header as follows:
const formData = new FormData();
formData.append('action', 'ADD');
formData.append('param', 0);
formData.append('secondParam', 0);
formData.append('file', new Blob(['test payload'], {
type: 'text/csv',
}));
axios({
url: 'http://localhost:5000/api/hello',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
});
Two things: I am using url, not uri. Also, please insert your own form data and url. Inspecting the request, which has been replied successfully, this is what I get for the request header:

After hours trying to make it work, I realized that a multipart/form-data needs a boundary that is generated dynamically depending on the amount of data that is being sent.
Here is the code that works for me:
const data = new FormData();
data.append('field_name', 'field_pictures');
data.append('files[file]', fs.createReadStream(filepath), filename);
const headers = {
'Content-Type': 'multipart/form-data',
'Authorization': 'here you can set your headers',
...data.getHeaders() // this line is the key
// you need to mix your headers with those generated by the form data
}
return axios.post(url, data, { headers });

You can do simply:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data; boundary=someArbitraryUniqueString';
It will set your headers for sure. However, I have been struggling with form data in React Native for a day and without success. After some experimental aproaches, I found out that everything works without debugger. I don't know why but with debugger, I have been sending empty body to the server.
What's more I didn't need to set headers as it is your question in this post.

According to #JMA answer,
import axios from 'axios';
export async function somefunction(data) {
const formData = new FormData(); // No imports needed
for(let key in userData) {
formData.append(key.toString(), data[key].toString())
}
return axios.post(`${ROUTE}`, formData, {
'Content-Type': 'multipart/form-data',
});
}
where: data is your payload to what you want to send. somefunction is function that send POST request to ROUTE.

Related

Invalid input file upload api platform

I'm trying to upload a file using api platform file upload. I'm using React-redux with redux-saga to make this request, but the server keeps throwing bad request response.
Api platform documentation says the following for making the request:
This endpoint accepts standard multipart/form-data-encoded data, but
not JSON data. You will need to format your request accordingly.
My Saga:
I tried appending my uploaded file to formData and use that as body for my request.
let data = new FormData();
data.append("file", action.payload.file)
const fileResponse = yield call(
fetch,
`${api.url}/api/media_objects`,
{
method: 'POST',
mode: 'no-cors',
body: data,
headers: { 'content-type': 'multipart/form-data' }
}
);
return console.log(fileResponse);
This is the api platform example request for posting a new media object
curl -X POST
"https://api.myroute/api/media_objects" -H
"accept: application/ld+json" -H "Content-Type: multipart/form-data"
-F "file=#1.6b.jpg;type=image/jpeg"
Api platform keeps returning a 400 error, which refers to invalid input. Any idea how the valid input should look like?
For my media object entity I followed the api platform documentation, so it looks exactly the same as in the docs
Details matter
headers: { 'content-type': 'multipart/form-data' }
It should be
headers: { 'Content-Type': 'multipart/form-data' }
There is no 'content-type', only 'Content-Type' header is defined (RFC) and widely accpeted.
I had a very similar issue recently (I can't remember the exact error), with API Platform (and the MediaObject entity), and React - redux (but no redux-saga).
I was able to fix it by removing the header part of my request :
headers: { 'content-type': 'multipart/form-data' }
So my new request looked exactly like that in my case :
const formData = new FormData();
formData.append('file', file);
return fetch(id, {
method: 'POST',
body: formData
})
...
I don't really know why, but it did the trick. Maybe it is handled automatically since we send a FormData object.
Hope it can work for you too !

What is the best way to enable CORS in React Application?

There are different ways to make a REST call in react-
e.g
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS.
Is there any other way that I can do this either in frontend or backend?
It depends on what HTTP library you are using.
See What is difference between Axios and Fetch?.
I usually use Axios, next what i do is creating a global instance and configuring Axios once.
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application.
Thanks to #henrik123 for good explanation:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library

Reactjs POST request using axios [duplicate]

This question already has answers here:
Why is an OPTIONS request sent and can I disable it?
(15 answers)
Closed 4 years ago.
I am trying to call a POST request in ReactJs using Axios, but getting an error. Code:
const payload =
{
device_id: 'ASDACCAS',
device_type: 'Web',
device_version: '1.2',
device_user_id: 'ASDBADKKK1234AS'
}
axios({
method: 'post',
url: 'https://stageapi.myapi.com/v3_2/user/splash',
data: payload,
headers: {
'secret-key': 'mysecretkey',
'Content-Type': 'application/json'
},
})
But this is giving me error:
Failed to load https://stageapi.myapi.com/v3_2/user/splash: Response for preflight does not have HTTP ok status.
Kindly help me whats wrong here. I am new to ReactJS and moving from mobile app development environment. I have been on this for so long, tried every method for axios POST including by appending formdata to body. Still the same.
EDIT:
Also, I am not sure if its something related to CORS. I have installed the the CORS plugin in chrome. Are there any changes that I need to make in API side code? Which is written in php.
When you want to make a post request, you need to stringify body request like this:
axios({
method: 'post',
url: 'https://stageapi.myapi.com/v3_2/user/splash',
data: JSON.stringify(payload),
headers: {
secret-key': 'mysecretkey',
'Content-Type': 'application/json'
},
})
axios.post('https://stageapi.myapi.com/v3_2/user/splash',
payload,
headers: {
'secret-key': 'mysecretkey',
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log(response.data);
});

Sending POST request weird issue

I'm quite new with ANGULAR and web development in general and I'm currently working on a web tool. Now I want this tool to send a POST request to a web service but Im encountering a weird bug. Now I have below code in my javascript:
var data_info = { test_id: 'TEST', model_id: 'TEST:TEST_ID' };
//data_info = JSON.stringify(data_info);
var request_json = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: data_info,
cache: false,
};
console.log(request_json);
$http(request_json).then(function successCallback(response) {
// response code here
}
Now this code currently doesn't pass the preflight request check and is always returning a 405. But if I change the line data: data_info in the request JSON into a new key let's say body: data_info it now successfully sends the request and I can confirm that the service is receiving it. I'm not sure what's the issue here and can't figure it out.
change your header to :
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
Please try

Can't send auth headers with axios

Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData},{
headers:{ 'Content-Type':'multipart/form-data',
Authorization:`Bearer ${token}`}
})
It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type
This should do the trick
axios({
method: 'POST',
url:`${API_URL}users/${23}/profile/main/update`,
headers: {
'Content-Type':'multipart/form-data',
'Authorization':`Bearer ${token}`},
data: formData
})
Refer docs for browser
Try to send as below:
var headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)
Try using Ajax call below:
import $ from 'jquery';
$.ajax({
url:`${API_URL}users/${23}/profile/main/update`,
processData: false,
contentType: false,
data : formData,
method : "POST",
headers: {
"Authorization": `Bearer ${token}`
}
});
I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set
WSGIPassAuthorization On
inside your virtualhost config.
Check this

Resources