Hi just learn to use js and react-native. I cant use FormData it always shows unsupported bodyinit type. I want to send text rather then JSON.stringify. Can anyone help me? Thanks!
var data = new FormData() data.append('haha', 'input') fetch('http://www.mywebsite.com/search.php', { method: 'post', body: data }) .then((response) => response.json()) .then((responseData) => { console.log('Fetch Success=================='); console.log(responseData); var tempMarker = []; for (var p in responseData) { tempMarker.push({ latitude: responseData[p]['lat'], longitude: responseData[p]['lng'] }) } this.setState({ marker: tempMarker }); }) .catch((error) => { console.warn(error); }) .done();
To use FormData in React Native, we can use the FormData constructor. to define the submit function that creates a FormData instance. Then we call append with the key and value to add form data entries.
Here is my simple code FormData with react-native to post request with string and image.
I have used react-native-image-picker to capture/select photo react-native-image-picker
let photo = { uri: source.uri} let formdata = new FormData(); formdata.append("product[name]", 'test') formdata.append("product[price]", 10) formdata.append("product[category_ids][]", 2) formdata.append("product[description]", '12dsadadsa') formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})
NOTE you can change image/jpeg
to other content type. You can get content type from image picker response.
fetch('http://192.168.1.101:3000/products',{ method: 'post', headers: { 'Content-Type': 'multipart/form-data', }, body: formdata }).then(response => { console.log("image uploaded") }).catch(err => { console.log(err) }) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With