繁体   English   中英

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

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

我正在接收作为 POST 请求的 webhook URL 上的数据。 请注意,此请求的内容类型是application/x-www-form-urlencoded

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

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

如果您使用 Express.js 作为 Node.js Web 应用程序框架,请使用 ExpressJS body-parser

示例代码将是这样的。

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

接受的答案使用 express 和 body-parser 中间件来表达。 但是,如果您只想解析发送到 Node http 服务器的 application/x-www-form-urlencoded ContentType 的有效负载,那么您可以在没有 Express 额外膨胀的情况下完成此操作。

你提到的关键是http方法是POST。 因此,使用 application/x-www-form-urlencoded,参数将不会在查询字符串中编码。 相反,有效负载将在请求正文中发送,使用与查询字符串相同的格式:

param=value&param2=value2 

为了在请求正文中获取有效负载,我们可以使用 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') );

您必须使用特定的中间件告诉 express 处理 urlencoded 数据。

const express = require('express');
const app = express();

app.use(express.urlencoded({
    extended: true
}))

在您的路线上,您可以从请求正文中获取参数:

const myFunc = (req,res) => {
   res.json(req.body);
}

如果您使用的是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)

Express 4.16+ 已经实现了他们自己的 body-parser 版本,所以你不需要在你的项目中添加依赖项。

app.use(express.urlencoded()); //Parse URL-encoded bodies

Express.js 中身体解析器的非弃用替代方案

如果您正在创建一个没有 Express 或 Restify 等框架的 NodeJS 服务器,那么您可以使用 NodeJS 本机查询字符串解析器 内容类型application/www-form-urlencoded格式与查询字符串格式相同,因此我们可以重用该内置功能。

此外,如果您不使用框架,那么您实际上需要记住阅读您的身体。 请求将包含方法、URL 和标头,但不会包含正文,直到您告诉它读取该数据。 你可以在这里阅读: https : //nodejs.org/dist/latest/docs/api/http.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM