Danyx
Danyx

Reputation: 724

Empty Request body on express app

When trying to make a POST call to an express.js server the body is empty.

I'm using react and express, so I've had to enable CORS to allow the calls from different servers. The code is as follows:

Express

var express = require("express"),
app = express(), 
bodyParser = require("body-parser"),
cors = require("cors");

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

app.post("/register", function(req, res){
    console.log(req); 
});

app.listen(3000, function(){
    console.log("test started"); 
})

React

handleSubmit(event){
    console.log(this.state); 
    fetch('http://localhost:3000/register', {
        method: 'POST',
        headers: {
            'Accept': 'application/json'
            },
        body: {
            username: "asd",
            password: "asdd",
            }
    });
    event.preventDefault(); 
}

What am I missing here? I have done it with 'Content-Type': 'application/json' and the result is the same.

Upvotes: 1

Views: 531

Answers (1)

Dez
Dez

Reputation: 5838

You are missing to tell to your Express server that you will to use JSON. To accomplish that, you need to add this line before defining any route:

app.use(bodyParser.json());

Besides that you need to JSON.stringify the body payload in your React's component handleSubmit method, because as it is right now, it is not JSON valid.

And finally the proper header you have to set is:

 'Content-Type': 'application/json'

Thus you tell the server you are sending a JSON body payload.

Upvotes: 3

Related Questions