如何在节点服务器上读取以application / x-www-form-urlencoded格式接收的数据?

时间:2021-04-10 17:08:43

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.

我正在接收webhook URL上的数据作为POST请求。请注意,此请求的内容类型为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"?

这是服务器到服务器的请求。在我的节点服务器上,我只是尝试使用req.body.parameters读取接收到的数据,但结果值是“未定义”?

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?

那么如何读取数据请求数据呢?我需要解析数据吗?我需要安装任何npm模块吗?你能写一个解释案例的代码片段吗?

1 个解决方案

#1


10  

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

如果您使用Express.js作为Node.js Web应用程序框架,那么使用ExpressJS正文解析器。

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);
});

#1


10  

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

如果您使用Express.js作为Node.js Web应用程序框架,那么使用ExpressJS正文解析器。

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);
});