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?
body-parser is an NPM package that parses incoming request bodies in a middleware before your handlers, available under the req. body property. app.
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.
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.
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); });
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With