react native fetch not sending body content - react-native

I am new to fetch in react native and followed this tutorial.
I am trying to send a json body to an private api server, I checked the server log and found out that the body content is empty.
Here is the code in react native
authenticateLogIn(){
fetch('<URL>', {
method: 'POST',
header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: JSON.stringify({'username': '<username>', 'password':'<password>'})
})
.then((incoming) => incoming.json())
.then((response) => {
console.log(response.header);
Alert.alert(JSON.stringify(response.body));
})
.done();

Maybe because it shoueld be headers? (with the s)

It might be because your JSON body isn't being parsed correctly. bodyParser https://github.com/expressjs/body-parser is part of the middleware that parses request bodies and needs to be configured.
req.body kept coming back empty for me until I added app.use(bodyParser.json() into server.js file. Make sure you import body-parser.

Related

Axios in React Native doesn't provide Form-Data headers

I'm trying to upload a file via Axios (Version ^0.26.0) in React Native (Version 0.66.4) with the following code:
const formData = new FormData();
formData.append('image', {
uri: 'aFilePathProvidedByTheImagePicker',
name: 'file.jpg',
type: 'image/jpg'
});
const response = await this.axiosInstance.put('aCustomUrl', formData, {
headers: {
'Content-Type': 'multipart/form-data;',
},
});
But it always fails with the status code 400. I tried the requested endpoint with Postman and it works fine.
After some debugging and comparing the requests from axios and postman I found out that the Content-Length header is missing. Also a boundary in Content-Type isn't provided. See the screenshots below:
Postman:
Reicht Native Debugging:
I also read about the formData.getLengthSync() but in react native it leads to the error formData.getLengthSync is not a function
Does anyone has a solution for this issue?
According to this post downgrading axios to version 0.24.0 works as a workaround.
(for debugging purpose I used the build in fetch-api which works as expected. but I'd prefer using axios for using a shared instance with request and response interceptors)
This issues is solved in Axios Version 0.27.2 (https://github.com/axios/axios/issues/4460#issuecomment-1115163147)
Your code should work but you could try to add content-type to headers
"Content-Type": "multipart/form-data; boundary=" + formData .getBoundary(),

Why in React Native post request can't be sent?

I am using axios in react native project but at the time of post request through axios it gives an error
export const login = (email, password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email, password });
console.log(body)
const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config);
console.log('kk');
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(load_user());
};
On postman this axios request is executing successfully and on the same backend address my react JS project is working correctly and this axios request also get successful.
On react native project it gives following error.
I've also tried try and catch blocks but after execting axios.post line it goes to catch block .
I've tried the same request on Postman and it's successfully sent the post request and get the tokens
Solution 1
Check this. Maybe you should set android:usesCleartextTraffic="true" in your AndroidManifest.xml file.
Solution 2
I could suggest the next command which I personally always use when developing RN apps on Android using local emulators. adb reverse tcp:8081 tcp:8081.
Solution 3
Use concrete local ip-address instead of localhost alias. Check this.

React native 'Network error' with post Custom header and form data

I am trying to upload some data using axios post request and custom headers. Here is my code.
axios
.post('https://website.domain/api/ads/create', new FormData(), {
headers: {
Authorization: 'Bearer 123',
},
})
.then(res => {
this.setState({ message: JSON.stringify(res) });
})
.catch(res => {
this.setState({ message: JSON.stringify(res.response) });
});
this works fine with Expo (here is the source)
But when move to react native it does not work. It gives me the error:
{message:"Network error".....}
PS: other methods like post without authorization, get all are working except this one.
I found the solution! The trick was with uploading the file: with expo you need to remove //file prefix of file path while in react-native it should be preserved!

Uploading image to S3 on Postman works but it doesn't work when I use React Native Image Picker

My Rails API seems to be working fine, when I POST an image to S3 via postman.
However, when I use React Native image picker, I don't think I'm sending the parameters in the correct way.
I am currently sending the image uri as the image parameter (the uri of the image picked from the image picker). Should I be sending something else as the image parameter?
Here is a part of my async function to make a POST request to the Visions table:
let access_token = this.state.accessToken
try {
let response = await fetch('https://prana-app.herokuapp.com/v1/visions/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-User-Email': this.state.email,
'X-User-Token': this.state.accessToken
},
body: JSON.stringify({
vision: {
description: 'YOYOYOYOYO',
image: this.state.uploadFile
}
})
});
In this case, this.state.uploadfile is the response.uri that I am getting when I pick an image from Image picker, which is formatted like:
file:///Users/ozgecokyasar/Library/Developer/CoreSimulator/Devices/EDD6C498-DACD-433E-B96D-3A30BAE7BA6D/data/Containers/Data/Application/B549F09A-EB40-4D9A-B8A8-B003362BE49D/Library/Caches/ExponentExperienceData/%2540anonymous%252Fmanifestation-react-3ac1cbe2-549f-49e7-8506-ef29638d1643/ImagePicker/28EAA390-F814-4A80-A188-8592B642BEFA.jpg
I am getting a 500 error:
ActionView::Template::Error (to_model delegated to attachment, but attachment is nil):

Uploading videos using formdata in react native

Has anyone successfully uploaded a video via React Native Formdata()? The code below attempts to upload a .mov file from the camera roll URI but in fact only the first frame of the video (a JPEG) gets uploaded. What's the issue here?
var movVideo = {
uri: uriFromCameraRoll,
type: 'video/quicktime',
name: 'something.mov',
};
var body = new FormData();
body.append('video', movVideo);
body.append('title', 'A beautiful video!');
fetch('https://mysite/upload_asset', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: body,
}).then((response) => response.json())
.then((responseJson) => {
//only the first frame of the video got uploaded
console.log(responseJson);
});
Had the same issue. Looks like React Native does not return the correct stream for videos with asset library URIs. Pictures seem to work fine. I would need to dig deeper before submitting an issue though.
I suggest you take a look at react-native-fetch-blob, which provides an improved fetch polyfill with Blob support. This implementation handles videos from the camera roll just fine. Also, the changes needed to use this module are minimal (include the polyfill, wrap URI with RNFetchBlob.wrap).