Express bodyparser isn't working properly

50
August 01, 2019, at 10:00 PM

To set up my bodyparser I use the following code:

const express = require('express')
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

Now if I have the following POST route in my express router:

var router = require('express').Router();
router.post('/sendadvertisement', async (req, res) => {
  console.log(req.body)
});

The result is [Object: null prototype] {advertisement: 'test'} -> My req.body isn't empty because it's in json format in my console output.

I don't really understand how this result can happen because I defined that the body should be in json format. I also tried it with app.use(express.json()), doesn't work either.

Answer 1

I replaced router with app and everything worked fine.

Router.get/post etc is only for defining sub routes after after you mounted a middelware function like app.use('route') that handels the Route. If you want to use the router you should mount the route using app.use(...) and then declare the post using router.post(...)

Also See: Difference Between app.use() and router.use() in Express

const express = require('express')
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.post('/sendadvertisement', async (req, res) => {
    console.log(req.body)
});
app.listen(8000, () => {
    console.log('Example app listening on port 8000!')
});
READ ALSO
How to initialize two dimensional array in worker thread script in node.js

How to initialize two dimensional array in worker thread script in node.js

Iam writing a nodejs application which calculates the leveshtein distance over multiple and long strings/texts

40
javascript function to get all the days of a week

javascript function to get all the days of a week

I am trying to get an array of all days in a week like today is Aug 1st so i need to get an array of this week which will look like

27
Modifying DOM nodes via JS causes memory leaks

Modifying DOM nodes via JS causes memory leaks

I'm working on a web template on WordPress that replaces the content of a specific div each period of time using jQueryHowever after a few loops the page crashes and the performance monitor of Chrome shows that the number of DOM nodes has increased on each iteration...

32
How comparate attributes of multiple fields with array

How comparate attributes of multiple fields with array

I am trying to comparator all attribute of the inputs with array is coming with those attributes name are in lowercases in DOM those are not lowercases

20