Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read the data received in application/x-www-form-urlencoded format on Node server?

I'm receiving data on a webhook URL as a POST request. Note that the content type of this request is application/x-www-form-urlencoded.

It's a server-to-server request. And On my Node server, I simply tried to read the received data by using req.body.parameters but resulting values are "undefined"?

So how can I read the data request data? Do I need to parse the data? Do I need to install any npm module? Can you write a code snippet explaining the case?

like image 488
Sowmay Jain Avatar asked Feb 09 '17 04:02

Sowmay Jain


People also ask

What is Bodyparser Urlencoded in node JS?

body-parser is an NPM package that parses incoming request bodies in a middleware before your handlers, available under the req. body property. app.

Why we use Urlencoded in node JS?

urlencoded() is a built-in middleware in Express. js. The main objective of this method is to parse the incoming request with urlencoded payloads and is based upon the body-parser. This method returns the middleware that parses all the urlencoded bodies.

What is the difference between Express JSON and express Urlencoded?

So the difference is express. json() is a body parser for post request except html post form and express. urlencoded({extended: false}) is a body parser for html post form.


2 Answers

If you are using Express.js as Node.js web application framework, then use ExpressJS body-parser.

The sample code will be like this.

var bodyParser = require('body-parser'); app.use(bodyParser.json()); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies  // With body-parser configured, now create our route. We can grab POST  // parameters using req.body.variable_name  // POST http://localhost:8080/api/books // parameters sent with  app.post('/api/books', function(req, res) {     var book_id = req.body.id;     var bookName = req.body.token;     //Send the response back     res.send(book_id + ' ' + bookName); }); 
like image 52
samith Avatar answered Oct 11 '22 19:10

samith


You must tell express to handle urlencoded data, using an specific middleware.

const express = require('express'); const app = express();  app.use(express.urlencoded({     extended: true })) 

And on your route, you can get the params from the request body:

const myFunc = (req,res) => {    res.json(req.body); } 
like image 42
Joao Barbosa Avatar answered Oct 11 '22 17:10

Joao Barbosa