0

I have a very simple backend server built in Node/Express that accepts a post request via

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json())

app.post('/auth/login', (req, res) => {
  console.log(req.body);
  res.send(req.body);
});

When I send a POST to this via Postman with key/value in the body it returns in Postman as expected and I can see in my NodeJS console that the exchange is happening via the console.log. However, when I do the same thing with React, it just logs an empty object.

This is my React:

handleSubmit(e) {
  e.preventDefault();
  const { email } = this.state;

  fetch('/api/login', {
    method: 'POST',
    headers: {
      'Content-Type':'application/json'
    },
    body: {
      "email": email
    }
  });

  console.log("EMAIL", email)
}

I have state being updated as the user types in their email and when they click the submit button it triggers this handleSubmit().

However the output is a lackluster empty {}

I am not sure what I am doing wrong here that the API wouldn't log the state? React logs the data getting posted to the API and it looks valid.

Update

Here is the code that is updating the state:

 handleChange(e) {
   const email = e.target.value;

   this.setState({
     email,
   });
 }

Update, I wasn't using .then() to return the data hence why I was getting an empty object.

3
  • can you post your setState function which changes the email? Commented Jan 15, 2018 at 15:50
  • 2
    fetch returns a promise and you need to call then() on it. Commented Jan 15, 2018 at 15:50
  • @MarouenMhiri updated my post at the bottom of it. Commented Jan 15, 2018 at 22:14

1 Answer 1

3
fetch('/api/login', {
    method: 'POST',
    headers: {
      'Content-Type':'application/json'
    },
    body: {
      "email": email
    }
  }).then(res => console.log(res));

you need use .then()

Sign up to request clarification or add additional context in comments.

1 Comment

This was it. Thank you! I am new to using fetch for POST requests. It's been all get requests up until now. It makes total sense that my code was incomplete without the .then()

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.