简体   繁体   English

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

[英]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.我正在接收作为 POST 请求的 webhook URL 上的数据。 Note that the content type of this request is application/x-www-form-urlencoded .请注意,此请求的内容类型是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?我需要安装任何 npm 模块吗? Can you write a code snippet explaining the case?你能写一个解释这个案例的代码片段吗?

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

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

The key thing you mentioned is the http method is POST.你提到的关键是http方法是POST。 Consequently, with application/x-www-form-urlencoded, the params will not be encoded in the query string.因此,使用 application/x-www-form-urlencoded,参数将不会在查询字符串中编码。 Rather, the payload will be sent in the request body, using the same format as the query string:相反,有效负载将在请求正文中发送,使用与查询字符串相同的格式:

param=value&param2=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.为了在请求正文中获取有效负载,我们可以使用 StringDecoder,它以保留编码的多字节 UTF8 字符的方式将缓冲区对象解码为字符串。 So we can use the on method to bind the 'data' and 'end' event to the request object, adding the characters in our buffer:所以我们可以使用 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') );

You must tell express to handle urlencoded data, using an specific middleware.您必须使用特定的中间件告诉 express 处理 urlencoded 数据。

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

Express 4.16+ has implemented their own version of body-parser so you do not need to add the dependency to your project. Express 4.16+ 已经实现了他们自己的 body-parser 版本,所以你不需要在你的项目中添加依赖项。

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

Non-deprecated alternative to body-parser in Express.js Express.js 中身体解析器的非弃用替代方案

If you are creating a NodeJS server without a framework like Express or Restify, then you can use the NodeJS native querystring parser .如果您正在创建一个没有 Express 或 Restify 等框架的 NodeJS 服务器,那么您可以使用 NodeJS 本机查询字符串解析器 The content type application/www-form-urlencoded format is the same as the querystring format, so we can reuse that built-in functionality.内容类型application/www-form-urlencoded格式与查询字符串格式相同,因此我们可以重用该内置功能。

Also, if you're not using a framework then you'll need to actually remember to read your body.此外,如果您不使用框架,那么您实际上需要记住阅读您的身体。 The request will have the method, URL, and headers but not the body until you tell it to read that data.请求将包含方法、URL 和标头,但不会包含正文,直到您告诉它读取该数据。 You can read up about that here: https://nodejs.org/dist/latest/docs/api/http.html你可以在这里阅读: https : //nodejs.org/dist/latest/docs/api/http.html

暂无
暂无

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

相关问题 如何在 node.js 中发布内容类型 ='application/x-www-form-urlencoded' 的数据 - how to post data in node.js with content type ='application/x-www-form-urlencoded' 具有 application/x-www-form-urlencoded 格式的 Node.js Axios POST 请求? - Node.js Axios POST request with application/x-www-form-urlencoded format? 如何在节点js中使用参数为application / x-www-form-urlencoded类型的POST调用 - How to consume POST call where parameter is of type application/x-www-form-urlencoded in node js node js 如何通过发送数据调用webapi( x-www-form-urlencoded ) - node js how to call webapi( x-www-form-urlencoded ) by sending data 如何使用节点请求发送承载令牌和x-www-form-urlencoded数据 - How to send bearer token and x-www-form-urlencoded data using Node Request 如何使用 Axios 在 application/x-www-form-urlencoded 中编码 JSON 数据? - How to encode JSON data in application/x-www-form-urlencoded using Axios? 如何在nodejs中支持application / json,application / x-www-form-urlencoded和multipart / form-data的请求或响应主体 - how to support request or response bodies for application/json, application/x-www-form-urlencoded and multipart/form-data in nodejs x-www-form-urlencoded 格式 - 在 node.js 中使用 https - x-www-form-urlencoded format - using https in node.js 节点js如何识别邮递员扩展客户端请求来自“表单数据”或“ x-www-form-urlencoded” - node js how to identify postman extention client request came from “form-data” or “x-www-form-urlencoded” 使用application / x-www-form-urlencoded使用node.js在发布请求中发送数组 - Send Array in post request using node.js using application/x-www-form-urlencoded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM