0

I have a react app which calls an API when the user clicks login. However, the response that react native receives is different than the intended response.

React Native code:

login() {
    this.setState({isLoading: true})
    return fetch(process.env.API_USER + "/signin", {
        method: "POST", 
        headers: {
            Accept: "application/json", 
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            username: this.state.username, 
            password: this.state.password
        })
    }).then((response) => {
        console.log(`\n\n\n\nRESPONSE---->${JSON.stringify(response)}\n\n\n\n`)
        this.setState({isLoading: false})
    })
    .catch((error) => {
        console.log((`\n\n\n\nERROR---->${error}\n\n\n\n`))
        this.setState({isLoading: false})
    })
}

Console response:

RESPONSE---->{"type":"default","status":401,"ok":false,"headers":{"map":{"via":"1.1 vegur","date":"Thu, 27 Sep 2018 18:10:42 GMT","server":"Cowboy","etag":"W/"17-wIxJlIRlPQbTEtBjbmLpTqPMWNo"","connection":"keep-alive","cache-control":"public, max-age=0","x-powered-by":"Express","content-length":"23","access-control-allow-credentials":"true","access-control-allow-origin":"","access-control-allow-methods":"","access-control-allow-headers":"Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers","content-type":"application/json; charset=utf-8"}},"url":"abc.com","_bodyInit":{"_data":{"size":23,"offset":0,"blobId":"f4012672-62b8-4b52-be6f-06446874981c"}},"_bodyBlob":{"_data":{"size":23,"offset":0,"blobId":"f4012672-62b8-4b52-be6f-06446874981c"}}}

Expected API response:

RESPONSE---->{"message": "Auth Fail"}

// ----------OR---------- //

RESPONSE---->{"message": "Auth Successfull"}

3 Answers 3

0

As the previous answers have noted, the response object has a .json() function which returns a promise (which resolves to the actual data).

Also you can structure the code much better with async/await

login = async () => {
  const options = {
    method: "POST",
    headers: {
      Accept: "application/json", 
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      username: this.state.username, 
      password: this.state.password
    }),
  };
  this.setState({isLoading: true});

  try {
    const response = await fetch(`${process.env.API_USER}/signin`, options);
    const responseData = await response.json(); // This is what you're missing

    this.setState({isLoading: false});
  } catch (error) {
    // Do something about the error
    console.log((`\n\n\n\nERROR---->${error}\n\n\n\n`));
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a TON!! I've been dealing with this issue for a long time. Thanks for solving it! Works perfectly!
If you don't mind, I have another issue with react native here: stackoverflow.com/q/52872893/10387115. It would mean a lot if you can take a look. Thanks in advance!
0

In document basic structure of fetch request defined here. from the document, you can try this one

  .then((response) => response.json())
        .then((resJSON) => {
           console(resJSON);
           this.setState({isLoading: false})
        })
        .catch((error) => {
           console.log(error)
           this.setState({isLoading: false})
        })

Comments

0

You need to have another .then that will resolve the response and converts it into JSON:

.then(response => response.json())
.then(data => {
    // now you can get your server response
    console.log(data)
 })    

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.