node.js - 无法访问 HTTP 服务器中的 POST 数据
问题描述
我正在开发一个用于单元测试的小型 HTTP 服务器。代码如下。
为什么该body
值在中可用req.on()
但在中不可用res.end()
?
复制
- 运行服务器
const WebhookServer = require('./webhook_server');
const server = new WebhookServer();
server.listen();
- 运行客户端
$ curl -XPOST http://localhost:1088 -d '{"num":1}'
{"method":"POST","body":"","type":"test"}
- 服务器日志
last body:
body: {"num":1}
last body:
body: {"num":1}
服务器代码
const http = require('http')
const kill = require('kill-port');
class WebhookServer {
constructor({ port = 1088, host = 'localhost' } = {}) {
this.port = port;
this.host = host;
}
listen() {
this.server = http.createServer((req, res) => {
if (['POST', 'PUT'].includes(req.method)) {
let body = '';
req.on('data', (data) => {
body += data;
console.log('body:', body);
});
res.writeHead(200, { 'Content-Type': 'application/json' });
console.log('last body:', body);
res.end(JSON.stringify({ method: req.method, body, type: 'test' }));
} else { // GET, DELETE
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ method: req.method, type: 'test' }));
}
});
this.server.listen(this.port, this.host);
}
kill() {
return kill(this.port);
}
}
module.exports = WebhookServer;
解决方案
您需要让服务器完成读取传入数据。
作为req
一个可读流,如果你res.end
在req.on("end")
事件处理程序中这样做,它应该可以工作。
检查以下对我有用的代码 -
const http = require('http')
const kill = require('kill-port');
class WebhookServer {
constructor({ port = 1088, host = 'localhost' } = {}) {
this.port = port;
this.host = host;
}
listen() {
this.server = http.createServer((req, res) => {
if (['POST', 'PUT'].includes(req.method)) {
let body = '';
req.on('data', (data) => {
body += data;
console.log('body:', body);
});
// wait for the reading process to finish
req.on("end", () => {
res.writeHead(200, { 'Content-Type': 'application/json' });
console.log('last body:', body);
res.end(JSON.stringify({ method: req.method, body, type: 'test' }));
})
} else { // GET, DELETE
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ method: req.method, type: 'test' }));
}
});
this.server.listen(this.port, this.host, () => {
console.log("started!");
});
}
kill() {
return kill(this.port);
}
}
module.exports = WebhookServer;
要求
curl -XPOST http://localhost:1088 -d '{"num":1}'
输出
{"method":"POST","body":"{\"num\":1}","type":"test"}
推荐阅读
- syntax - 如何在不将语法设置为纯文本的情况下禁用 SublimeREPL 中的语法突出显示?
- sql - 如何从具有大行的表中选择数据,其中列如 column1%column2
- javascript - 避免用户多次点击提交按钮?
- autohotkey - ctrl+s 未在 autohotkey 脚本中发送
- ios - Swift 5 尝试接受和解析 Firebase 动态链接和深度链接 - 出现错误,并且从不执行我的代码 - 软件导致连接中止
- postgresql - 在 PostgreSQL 中,散列子计划是什么意思?
- bash - cd 遇到问题并返回目录
- javascript - 如何延迟代码直到窗口调整大小结束
- azure - 在 arm 模板中配置自定义自动修复规则(有没有办法添加具有多种操作类型的多个触发条件?)
- vb.net - 如何在 vb.net 中的同一文件上保持写入信息?