0

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.

Gilles Heinesch
  • 2,889
  • 1
  • 22
  • 43

3 Answers3

-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!')
});
S. Kuiter
  • 99
  • 9
-1

If you are using express then you can use this code to set your body parser.

app.use(express.json( {extended:false} ));
app.use(express.urlencoded({extended: false}));
Udit
  • 129
  • 2
  • 6
-1
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

This is also giving error, page is scrolling after submission.

Umut Sirin
  • 2,462
  • 1
  • 21
  • 31