1

I am submitting a form and the following gets called...

handleLogin(){
    fetch('http://localhost:8080', {
        method: 'post',
        body: JSON.stringify({
         username: this.state.username,
         password: this.state.password
        })
    });

}

It makes a POST request to my restAPI. The request works, but the data is not passed...

app.post('/', function(req, res, next) {
    console.log(req.body.username);
    ....

This prints out undefined, meaning password and username are not passed through the call. What am I doing wrong?

8
  • First thing you should do is check the Network tab in Chrome Developer Tools. There, you can see what data is exactly sent in the request. I would also recommend printing this.state before calling fetch(). Commented Oct 11, 2016 at 4:15
  • @MouadDebbar I did print this.state, its all good. Ill check the network Commented Oct 11, 2016 at 4:16
  • @MouadDebbar so I check the network, and under header tab > Form Data, it tells me that the right credentials were passed. I'm very confused as to why I cannot retrieve it Commented Oct 11, 2016 at 4:21
  • Ok this means one thing. Node is not parsing your data as json. Could you print req.body? You will need to use bodyParse.json() as a middleware. Commented Oct 11, 2016 at 4:25
  • @so when I print req.body I get an empty array, {}, also on POST I get redirect to a page cannot POST but yet it still console.log everything inside my app.post Commented Oct 11, 2016 at 4:27

2 Answers 2

1

Express by default doesn't parse the body of the request. In order to enable parsing, you will need to use a middleware such as body-parser. You can find some information in the express docs.

Also, the client side needs to indicate that it's sending json data. That can be achieved with the Content-Type header. There is a pretty good tutorial about fetch() here. You can jump directly to the Request Headers section which is relevant for your question.

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

Comments

0
  var express = require("express");
    var app = express();
    var bodyParser = require('body-parser');
    const PORT = process.env.PORT || 7070;
    const BASEURL = process.env.BASEURL || 'http://localhost/7070';

    app.use(bodyParser.urlencoded({extended:true}));
    app.listen(PORT, function() {   console.log('Server running on'+BASEURL);
     });

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.