0

for some reason I can see my req.body in my express server on my route

req body is [Object: null prototype] { '{"password":"xxxxxxxx"}': '' }

but when I log req.body.password (the object key) I get

req body is undefined

here's my index router for reference in my express app

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
const path = require('path');

/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {

  console.log('req body is',req.body.password)
  res.send("passconfirmed");
});

module.exports = router;
monsterpiece
  • 739
  • 2
  • 12
  • 34

2 Answers2

1

If you're using body-parser

You have to enable the body parser to work, before using parsed data in you routes.

In your main module where you import all your libs, you need to declare express to use body-parser middleware.

const express = require('express')
const bodyparser = require('body-parser')
const app = express()
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended : true }))
...
//here comes your routes

After including the bodyparser middleware you can use parsed data in your routes.

Notice that if you're using express version >= 4.16, body parser comes bundled with express. You just have to use change your code to:

const express = require('express')
const app = express()
app.use(express.json()); //this line activates the bodyparser middleware
app.use(express.urlencoded({ extended: true }));

Doing so you can safely remove body-parser package.

Danizavtz
  • 3,166
  • 4
  • 24
  • 25
1

To access the content of the body, Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

You need to install a body-parser package.

npm i body-parser --save

Now import body-parser in your project. It should be called before your defined route functions.

const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const path = require('path');

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

/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {

  console.log('req body is',req.body.password)
  res.send("passconfirmed");
});

module.exports = router;
Prathamesh More
  • 1,470
  • 2
  • 18
  • 32