What is the use of body-parser? - node.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/process_post', urlencodedParser, function (req, res)
Can anyone please explain the purpose of above three lines of code and what is the use of body-parser?

The bodyParser will populate the req.body property with the parsed body from the request. With the Line 1 you will just get one to you use in your class via require.
Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings. The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded.
With the last line you just saying that this route you has defined will use the bodyparser you have defined
the most of the stuff i have copied from https://github.com/expressjs/body-parser. so may take a look at this link

Suppose you have POST route handler that accepts some parameters and works accordingly. Now you make a request from your front end app or mobile app. You pass some parameters to this request. Now what body Parser does is it extracts the parameter from the request, parses it and makes it available req.body and you can access the parameters by their specific name
This is a middleware and it parses UTF-8 encoded bodies. It helps to parse URL encoded data like JSON objects
This is a way of defining that a particular route will make use of the urlEncodedParser

You can simply use
const express = require('express')
const app = express();
app.use(express.urlencoded({extended: false}))
app.listen(//your port)
// Thats it

Related

Node js, Express - Unable to retrieve form data using post method

My application has post route that accepts the data from postman client. I have written following code to retrieve value of form and print it:
var express = require('express');
req.app.use(express.urlencoded());
req.app.use(express.json());
console.log('req.body.name --> ' + req.body.name);
Above code prints req.body.name --> undefined rather than name value given in field name
I also tried following code:
var express = require('express');
const bodyParser = require('body-parser');
req.app.use(bodyParser.urlencoded({ extended: true }));
console.log('req.body.name --> ' + req.body.name);
Above code too prints req.body.name --> undefined rather than name value given in field name.
Can anyone please guide me on to resolve the issue in retrieving field name?
Used multer to solve this based on inputs from req.body is empty on express POST call.
Posting to benefit others.
var multer = require('multer');
var upload = multer() ;
app.post('/test', upload.array(), function (req, res, next) {
console.log(req.body.name);
});
Cheers :)
In your code, req is used, but req is not declared.
You wrote that you used POST, but you didn't write an entry point for POST.
Please try the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
app.post('/users', (req, res) => {
console.log(req.body);
console.log(req.body.name);
res.send(req.body.name);
});
app.listen(3000);
The port number is not necessarily 3000.
Use your Postman configuration.
In your code, proper imports are not there.
1. For Any node application these imports are mandatory
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
2. Use these imports properly like
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
3. Then use any Http Method like Get, Post, Put, and Delete
Example -
app.post(‘/sample’, (req, res) => {
// name must be in your request body while requesting for the above API
console.log(req.body.name);
res.send(req.body.name);
});
4. Add the port lister on which Application should run
app.listen(9000);

Can't get POST data using NodeJS/ExpressJS and Postman

This is the code of my server :
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.post("/", function(req, res) {
res.send(req.body);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".
However I keep getting an empty object in the response. The req.body property is always empty.
Did I miss something?
Add the encoding of the request. Here is an example
..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..
Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw
Edit for use of raw
Raw
{
"foo": "bar"
}
Headers
Content-Type: application/json
EDIT #2 Answering questions from chat:
why it can't work with form-data?
You sure can, just look at this answer How to handle FormData from express 4
What is the difference between using x-www-form-urlencoded and raw
differences in application/json and application/x-www-form-urlencoded
let express = require('express');
let app = express();
// For POST-Support
let bodyParser = require('body-parser');
let multer = require('multer');
let upload = multer();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/sayHello', upload.array(), (request, response) => {
let a = request.body.a;
let b = request.body.b;
let c = parseInt(a) + parseInt(b);
response.send('Result : '+c);
console.log('Result : '+c);
});
app.listen(3000);
Sample JSON and result of the JSON:
Set Content-typeL application/JSON:
I encountered this problem while using routers. Only GET was working, POST, PATCH and delete was reflecting "undefined" for req.body. After using the body-parser in the router files, I was able to get all the HTTP methods working...
Here is how I did it:
...
const bodyParser = require('body-parser')
...
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
...
...
// for post
router.post('/users', async (req, res) => {
const user = await new User(req.body) // here is where I was getting req.body as undefined before using body-parser
user.save().then(() => {
res.status(201).send(user)
}).catch((error) => {
res.status(400).send(error)
})
})
For PATCH and DELETE as well, this trick suggested by user568109 worked.
On more point I want to add is if you created your project through Express.js generator
in your app.js it also generates bellow code
app.use(express.json());
if you put your body-parser above this code the req.body will return null or undefined
you should put it bellow the above code see bellow for correct placement
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
I experienced the same issue. I tried all that had been suggested here. I decided to console log the value of the request object. It's a huge object. Inside this object I saw this query object carrying my post data:
query: {
title: 'API',
content: 'API stands for Application Programming Interface.'
}
So it turns out that request.query, and not request.body, contains the values I send along with my post request from Postman.

How to use `bodyParser.raw()` to get raw body?

I am creating a web API using Express.
The feature is to allow API users to send a file to the server.
Here's my app setup code:
var express = require('express');
var path = require('path');
// ...
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
// API routes
var images = require('./routes/api/img');
var app = express();
app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/api', images);
// ...
module.exports = app;
Please notice that I am using app.use(bodyParser.raw());.
How do I get the raw bytes from POST requests?
const express = require('express');
const router = express.Router();
/* POST api/img */
router.post('/img', function(req, res, next) {
// how do I get the raw bytes?
});
module.exports = router;
if you want to send a raw data and get with body parser you just configure this way:
app.use(bodyParser.raw({ inflate: true, limit: '100kb', type: 'text/xml' }));
That behavior doesn't corrupt the body content.
To parse all content types I use:
app.use(
express.raw({
inflate: true,
limit: '50mb',
type: () => true, // this matches all content types
})
);
To get the raw body in just a single route:
app.put('/upload', express.raw({ inflate: true, limit: '50mb', type: () => true }), async (req, res) => {
res.json({ bodySize: req.body.length });
});
In that case note that the previously app.use()'d body parsers (json for example) are executed first - so check that req.body is indeed a Buffer, otherwise a malicious caller could send something like {"length":9999999} with Content-Type: application/json.
The parsed body should be set on req.body.
Keep in mind that middleware is applied in the order you set it with app.use, my understanding is that applying the bodyParser multiple times as you have will attempt to parse the body in that order, leaving you with the result of the last middleware to operate on req.body, i.e. since both bodyParser.json() and bodyParser.raw() both accept any inputs, you will actually end up attempting to parse everything from a Buffer into JSON.

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"]

parse form data in nodejs service

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
//app.use(express.urlencoded());
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
extended: true`enter code here`
}));
app.post('/register', function (req, res) {
console.log("inside log");
console.log(req.body);
var username = req.body.username;
console.log(username);
});
As I have used urlencoded() whenever I post data in form data, I do not get data in req.body. i have attached image of postman
in case I send data in x-www-urlencoded then I get data
Please give me a solution to parse the data. I want to pass it in form data because I will be uploading an image too. So for image form data is must
You need use connect-multiparty npm module.
global.app = module.exports = express();
var multipart = require('connect-multiparty');
app.use(multipart());
You not set content-type in postman because node server automatically set his content-type in header according to form-data file.

Resources