Sow*_*ain 16 http-post node.js
我正在接收webhook URL上的数据作为POST请求.请注意,此请求的内容类型是application/x-www-form-urlencoded.
这是服务器到服务器的请求.在我的节点服务器上,我只是试图通过使用读取接收到的数据,req.body.parameters但结果值是"未定义"?
那么如何读取数据请求数据呢?我需要解析数据吗?我需要安装任何npm模块吗?你能写一个解释案例的代码片段吗?
小智 22
如果您使用Express.js作为Node.js Web应用程序框架,那么使用ExpressJS 正文解析器.
示例代码将是这样的.
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);
});
Run Code Online (Sandbox Code Playgroud)
Don*_*ato 10
接受的答案使用 Express 和用于 Express 的 body-parser 中间件。但是,如果您只想解析发送到 Node http 服务器的 application/x-www-form-urlencoded ContentType 的有效负载,那么您可以完成此任务,而无需使用 Express 的额外膨胀。
你提到的关键是http方法是POST。因此,使用 application/x-www-form-urlencoded,参数将不会在查询字符串中进行编码。相反,有效负载将在请求正文中发送,使用与查询字符串相同的格式:
param=value¶m2=value2
Run Code Online (Sandbox Code Playgroud)
为了获取请求正文中的有效负载,我们可以使用 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') );
Run Code Online (Sandbox Code Playgroud)
您必须告诉express 使用特定的中间件来处理urlencoded 数据。
const express = require('express');
const app = express();
app.use(express.urlencoded({
extended: true
}))
Run Code Online (Sandbox Code Playgroud)
在您的路线上,您可以从请求正文中获取参数:
const myFunc = (req,res) => {
res.json(req.body);
}
Run Code Online (Sandbox Code Playgroud)
如果您要创建一个没有 Express 或 Restify 等框架的 NodeJS 服务器,那么您可以使用 NodeJS 原生查询字符串解析器。内容类型application/www-form-urlencoded格式与查询字符串格式相同,因此我们可以重用该内置功能。
另外,如果您没有使用框架,那么您需要真正记住阅读您的身体。该请求将包含方法、URL 和标头,但不包含正文,直到您告诉它读取该数据。您可以在这里阅读相关内容:https ://nodejs.org/dist/latest/docs/api/http.html
| 归档时间: |
|
| 查看次数: |
14840 次 |
| 最近记录: |