Reputation: 150
I have a react-native app that needs to send video/images to my server. I already know that normal posts work but when I attempt to send a formData object, it seems to never leave the phone. Here is my code.
// method = 'POST';
// body = new formData();
// body contains text data and image/video file
const post = (url, body, token, method) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Authorization', 'Bearer' + token);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=---------------------------7692764ac82');
xhr.send(body);
console.log(xhr);
return xhr.response;
}
body is a formData object that contains an image/video. In the object that xhr prints at the console log the _response contains "Binary FormData part needs a content-type header." But it seems I set it correctly right?
Please help, there are other similar questions but I have run out of ideas. I have also tried using fetch with no success.
Upvotes: 3
Views: 11133
Reputation: 20467
The error message is not about the content-type header for the request (which you have set), it's about the content-type header for the part (which you did not show, so we have to assume it is missing).
When you add the parts to the FormData
, don't forget to include a type
. Example for an image:
const body = new FormData();
// ...
body.append('image', {
uri: 'file:///...',
type: 'image/jpeg', // <- Did you miss that one?
name: 'someName',
});
With the type
properly set, the React Native runtime should add a content-type
header for the part. This is done in FormData.js
at line 79 in v0.46.0 (wherein value
is the value for your type
property):
if (typeof value.type === 'string') {
headers['content-type'] = value.type;
}
So, when type
is missing, then content-type
header for the part is missing, and then on Android you end up here, where you can see the origin of your error message.
This exact error and root cause is discussed in that GitHub issue.
Upvotes: 25