0

I've tried this piece of code:

fetch("http://localhost:5000/api/signin", {
  method: "post",
  headers: {
    "Content-Type": "application/json",
    Authorization: "this-can-be-anything"
  },
  body: JSON.stringify({
    email: this.state.email,
    password: this.state.password
  })
})
  .then(response => {
    console.log(response);
    response.json();
  })
  .then(data => {
    console.log(data);
  });

It's a try to see if everything is good, if I try on Postman to call http://localhost:5000/api/signin everything work and here too but I don't get anything back. I get on network tab a call that get me the data I want, and another from the line I call the fetch with status 204.

No content, why?

3 Answers 3

1

You are not returning the promise returned by response.json(), so your promise chain is broken and undefined is given as argument to the last function.

Add the return keyword and it will work as expected.

fetch("http://localhost:5000/api/signin", {
  method: "post",
  headers: {
    "Content-Type": "application/json",
    Authorization: "this-can-be-anything"
  },
  body: JSON.stringify({
    email: this.state.email,
    password: this.state.password
  })
})
  .then(response => {
    return response.json();
  })
  .then(data => {
    console.log(data);
  });
Sign up to request clarification or add additional context in comments.

Comments

0

This issue occurs because you are not returning anything from

.then(response => {
  console.log(response);
  response.json();
})

If you add curly braces to an arrow function; then you need to add an explicit return. So change it to either:

.then(() => response.json())

or

.then(() => {
  return response.json();
})

And it should work.

Comments

0

Looks like you need to return the Promise returned by .json()

This can be cleaned up a bit using the modern ES7 feature of async/await avoiding the ubiquitous callback hell

const loginUser = async () => {

  const response = await fetch("http://localhost:5000/api/signin", {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: "this-can-be-anything"
    },
    body: JSON.stringify({
      email: this.state.email,
      password: this.state.password
    })
  })

  const data = await response.json();

  console.log('[data]', data);

  return 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.