2

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 protected]',
            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?

1
  • Use instead catch(console.log) so as to inspect and debug what error you're facing. Commented Jul 4, 2019 at 22:57

1 Answer 1

1

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 protected]',
    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(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.