body parser logging empty object in express router - node.js

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;

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;

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.

Related

Nodejs bodyParser.raw on one route

I have the following in my index.js:
app.use(bodyParser.json());
But Stripe webhooks want this:
Match the raw body to content type application/json
If I change my index.js to the following:
app.use(bodyParser.raw({type: 'application/json'}));
It works fine. But all my other API routes will not work anymore. Here is my route:
router.route('/stripe-events')
.post(odoraCtrl.stripeEvents)
How can I change to the raw body for only this api route?
You can access to both at the same time by doing this:
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}))
Now the raw body is available on req.rawBody and the JSON parsed data is available on req.body.
Divide them into two routers '/api' and '/stripe-events' and indicate bodyParser.json() only for the first one:
stripeEvents.js
const express = require('express')
const router = express.Router()
...
router.route('/stripe-events')
.post(odoraCtrl.stripeEvents)
module.exports = router
api.js
const express = require('express')
const router = express.Router()
...
router.route('/resource1')
.post(addResource1)
router.route('/resource2')
.post(addResource2)
module.exports = router
const stripeEventsRouter = require('./routers/stripeEvents';
const apiRouter = require('./routers/api';
apiRouter.use(bodyParser.json());
stripeEventsRouter.use(bodyParser.raw({type: 'application/json'}));
app.use('/api', stripeEventsRouter);
app.use('/api', apiRouter);

How are Express middleware chained?

I have the following in app.js
var app = require("express")();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(require("./routes/admin");
...
And in ./routes/admin.js:
var router = require("express").Router();
var bodyParser = require("body-parser");
router.use(bodyParser.json());
router.get("/", (req, res)=> { res.send("test"); });
...
module.exports = router;
The main app already has bodyParser as a middleware, and app uses admin as a route. Is the router.use(bodyParser.json()) statement required in admin.js if I want to use it in admin.js? Would a request be parsed in app.js before continuing to admin.js?

The JSON data in request body is not getting parsed using body-parser

When I send a POST request using postman to localhost:8080/api/newUser with request body:
{name: "Harry Potter"}
At server end console.log(req.body) prints:
{ '{name: "Harry Potter"}': '' }
server.js
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
router.use(function(req, res, next) {
next();
});
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);
app.listen(8080);
What am I doing wrong?
In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use('/api', router);
app.listen(8080);
Change the request header
'Content-Type':'application/json'
So that bodyParser can parse the body.
*That is what works for me. i am using angular 2+ with express(body-parser)
I spent quite a bit of time trying to figure out how to pass objects from Axios as key-value pairs and eventually decided to go with an alternative because setting the Content-Type: "application/json" retuned an empty object.
If the above options don't work for you, I would consider:
Extracting the key (which should contain the entire
object)
Parsing the key
Accessing the values of the newly created objects
This worked for me:
var obj = (Object.keys(req.body)[0])
var NewObj = JSON.parse(obj)
var name = apiWords["Key1"]
var image = apiWords["Key2"]

ExpressJS Error: Body-Parser Deprecated

Question
I'm trying build a Node.js API, when write my server.js file, my code looks like this:
var express = require('express');
var express = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.get('/api/posts', function(req,res) {
res.json([
{
username: 'oscar',
body: 'hello'
}
])
})
app.listen(3000, function() {
console.log('Server Listening on', 3000)
})
However, in the command prompt I am getting this error:
body-parser deprecated bodyParser: use individual json.urlencoded
middlewares server.js:4:11
body-parser deprecated undefined extended: provide extended option
node_modules\body-parser\index.js:85:29
I tried changing this to :
app.use(bodyParser.urlencoded({ extended: true }));
and
app.use(bodyParser.urlencoded({ extended: false }))
like other posts suggest, but it still gives the same error. Not sure what to do now! Please help.
Thanks!
var app = express();
// configure body-parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
I had similar deprecated warning. Here's my original code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
Adding {extended: true} fixed the warning for me. Here's changed code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Unless you have a typo, change:
var express = require('body-parser');
var app = express();
app.use(bodyParser.json());
to:
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
Do have a look at what the request and response objects do here
You don't actually need the line app.use(bodyParser.urlencoded({extended: true}));
I've got it to work with the following code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
As log as you have app.user(bodyParser.json()); you shouldn't get the error.
You don't need body-parser module any more with current express.js versions (≥ 4.16).
Instead, use the json parser already included in express:
app.use(express.json())
Source: https://expressjs.com/en/changelog/4x.html#4.16.0
Don't use body-parser
In new versions of express, body parsing is now builtin. So, you can simply use
app.use(express.json()) //For JSON requests
app.use(express.urlencoded({extended: true}));
from directly express
You can uninstall body-parser using npm uninstall body-parser
Then you can simply get the POST content from req.body
app.post("/yourpath", (req, res)=>{
var postData = req.body;
//Or for string JSON body, you can use this
var postData = JSON.parse(req.body);
});

ExpressJS cannot get POST

The relevant part of my app.js is as follows
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var routes = require('./config/routes);
app.use('/', routes);
My route file is:
var express = require('express');
var router = express.Router();
var upgradesController = require('../../app/controllers/upgrades.server.controller');
// This should receive POST requests
router.post('/api/upgrades/device', upgradesController.create);
module.exports = router;
And finally my controller is
exports.create = function(req, res) {
res.send(req.body);
}
But this sends nothing. It's always an empty JSON value. I'm using PostMan for testing:
What is happening?
You're sending form-data, switch to x-www-form-urlencoded instead. You can also send "raw", and input valid JSON.

Resources