I'm having a bit of trouble setting up an API call for authentication in react native. I use the following code:
fetch('http://myserver.ngrok.io/auth/login', {
method: 'POST',
body: {
email: 'email@gmail.com',
password: 'password',
},
})
.then(() => {
this.props.navigation.navigate('Main');
})
.catch(() => {
this.props.navigation.navigate('Auth');
console.error('Request Failed');
});
I'm using ngrok, because at first, I thought I was having issues with my android emulator/device QR scanning not being able to connect to my computer's localhost. I have tested the api call to this ngrok endpoint in postman, and it has worked perfectly. However, the above code always gives me my Request Failed
.
I have tested this on both my android emulator and tunneling with my android phone via QR. Is this a syntax issue?
The correct way to use fetch to send JSON would be in your case:
fetch('http://myserver.ngrok.io/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'}
body: JSON.stringify({
email: 'email@gmail.com',
password: 'password',
}),
})
Note the JSON.stringify
and the header.
Also, fetch will be successful even in case of a server error, and the user could enter invalid credentials, so check the server response before redirecting to main:
.then(resp => resp.json())
.then(data => this.props.navigation.navigate(data.correctCredentials ? 'Main' : 'Auth'))
.catch(...)
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.