Home > Enterprise >  Why is the response different from the fetch post request?
Why is the response different from the fetch post request?

Time:10-16

Why is my token undefined when i make a post request like this:

let requestInfo = JSON.stringify({
      email: email,
      password: password,
    });
let requestOptions = {
      method: "POST",
      headers: { 'Content-Type': 'application/json' },
      body: requestInfo
    }
fetch('http://url/token', requestOptions).then(response => {
        response.json()
        setShowLoading(false);
      }).then(token => console.log(token)).catch(error => console.log(error))

The token => console.log(token) is always undefined, and when i log in with the wrong credentials the .catch(error => console.log(error)) does not fire

but when i make the post request like this is works perfectly fine:

const response = await fetch('http://url/token', requestOptions);
      const data = await response.json();
      console.log(data);

CodePudding user response:

You need to return response.json() inside the then clauses, in order to use it in the next then clause.

fetch('http://url/token', requestOptions).then(response => {
    setShowLoading(false);
    return response.json()
}).then(token => console.log(token)).catch(error => console.log(error))
  • Related