node.js 如何在 Node 服务器上读取以 application/x-www-form-urlencoded 格式接收的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42128238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read the data received in application/x-www-form-urlencoded format on Node server?
提问by Sowmay Jain
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.
我正在接收作为 POST 请求的 webhook URL 上的数据。请注意,此请求的内容类型是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.parametersbut 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 模块吗?你能写一个解释这个案例的代码片段吗?
回答by samith
If you are using Express.js as Node.js web application framework, then use ExpressJS body-parser.
如果您使用 Express.js 作为 Node.js Web 应用程序框架,请使用 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);
});
回答by Donato
The accepted answer uses express and the body-parser middleware for express. But if you just want to parse the payload of an application/x-www-form-urlencoded ContentType sent to your Node http server, then you could accomplish this without the extra bloat of Express.
接受的答案使用 express 和 body-parser 中间件来表达。但是,如果您只想解析发送到您的 Node http 服务器的 application/x-www-form-urlencoded ContentType 的有效负载,那么您可以在没有 Express 额外膨胀的情况下完成此操作。
The key thing you mentioned is the http method is POST. Consequently, with application/x-www-form-urlencoded, the params will not be encoded in the query string. Rather, the payload will be sent in the request body, using the same format as the query string:
你提到的关键是http方法是POST。因此,使用 application/x-www-form-urlencoded,参数将不会在查询字符串中编码。相反,有效负载将在请求正文中发送,使用与查询字符串相同的格式:
param=value¶m2=value2
In order to get the payload in the request body, we can use StringDecoder, which decodes buffer objects into strings in a manner that preserves the encoded multi-byte UTF8 characters. So we can use the on method to bind the 'data' and 'end' event to the request object, adding the characters in our buffer:
为了在请求正文中获取有效负载,我们可以使用 StringDecoder,它以保留编码的多字节 UTF8 字符的方式将缓冲区对象解码为字符串。所以我们可以使用 on 方法将 'data' 和 'end' 事件绑定到请求对象,在我们的缓冲区中添加字符:
const StringDecoder = require('string_decoder').StringDecoder;
const http = require('http');
const httpServer = http.createServer((req, res) => {
const decoder = new StringDecoder('utf-8');
let buffer = '';
req.on('data', (chunk) => {
buffer += decoder.write(chunk);
});
req.on('end', () => {
buffer += decoder.end();
res.writeHead(200, 'OK', { 'Content-Type': 'text/plain'});
res.write('the response:\n\n');
res.write(buffer + '\n\n');
res.end('End of message to browser');
});
};
httpServer.listen(3000, () => console.log('Listening on port 3000') );
回答by Marshal
If you are using restify, it would be similar:
如果您使用的是restify,它会是类似的:
var server = restify.createServer()
server.listen(port, () => console.log(`${server.name} listening ${server.url}`))
server.use(restify.plugins.bodyParser()) // can parse Content-type: 'application/x-www-form-urlencoded'
server.post('/your_url', your_handler_func)

