Marino
Marino

Reputation: 3

Getting an empty body using Express

I'm currently using express to handle a POST request, but when I POST using node-fetch, I send a body and then I console.log() the body received in express (server code). I get an empty object. Not sure why this is happening, I will include my code here below.

Server Code

const express = require('express');
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

// GET method route
app.get('/api/getHeartCount', function (req, res) {
    res.send('GET request')
});

  // POST method route
app.post('/api/sendHeart', function (req, res) {
    res.sendStatus(200);
    let fBody = JSON.stringify(req.body);
    console.log("Got body: " + fBody); // When this is run, I get this in the console: Got body: {}
});

app.listen(3000);

POST request code

const fetch = require("node-fetch");

(async () => {
    const body = { heartCount: 1 };

    const response = await fetch('http://localhost:3000/api/sendHeart', {
        method: "post",
        body: JSON.stringify(body)
    });
    const res = await response.text();

    console.log(res);
})();

Upvotes: 0

Views: 160

Answers (2)

MaieonBrix
MaieonBrix

Reputation: 1624

you used the wrong bodyParser

You must use the bodyParser.json() middleware like so in order to be able to parse json and access the body at req.body

// this snippet will enable bodyParser application wide
app.use(bodyParser.json())

// you can also enable bodyParser for a set of routes if you don't need it globally like so

app.post('/..', bodyParser.json())

// or just for a set of routes
router.use(bodyParser.json()

bodyParser.json([options]) Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).

from : https://www.npmjs.com/package/body-parser#bodyparserjsonoptions

NOTE : don't forget to add the Content-Type: application/json to your requests if you are sending a json type body

UPDATE : as @ifaruki said, express is shipped with a built-in json bodyParser accessible via express.json() from : https://expressjs.com/en/api.html#express.json

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

You should parse the body of your request

app.use(express.json());

With the newest express version you dont need body-parser

Upvotes: 1

Related Questions