简体   繁体   中英

React Native XHR multipart/form-data send data as [object Object]

I'm trying to send a multipart/form-data from React Native (Running on Simulator) to backend server using XHR with the following code

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://....url....');
let formdata = new FormData();
formdata.append('title','This is awesome');
xhr.send(formdata);

However in console log the Request Payload are shown as [object Object]

So I decided to take the same code and put it in an HTML file and run from Chrome browser and Request Payload from console log is showing as below which I was expecting it from React Native

------WebKitFormBoundaryGXwudBdBkJzBnPug
Content-Disposition: form-data; name="title"

This is awesome
------WebKitFormBoundaryGXwudBdBkJzBnPug--

I had the same issue and after a day of research I found that we have to apply a polyfill, because React Native environment differs from what you can find in browser or Node.js.

Put this line in your main index file, and you should be good:

global.FormData = global.originalFormData ? global.originalFormData : global.FormData;

for TypeScript define global first:

declare const global: any;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM