Skip to content
Advertisement

Node.js express – body of POST request is always empty

I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:

enter image description here

This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn’t seem to work no matter what I tried. My current implementation goes like this:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()

//Import static files
app.use(express.static('../public'))

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

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

app.listen(port, () => console.log("Server started"));

No matter what I try from other posts, it still does not seem to return me any data.

enter image description here

Does anyone have an idea how to fix this problem?

Advertisement

Answer

Why to you use ‘jsonParser’ in the app route? Try something like:

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

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

app.post('/post-test', (req, res) => {
    console.log('Got body:', req.body);
    res.sendStatus(200);
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement