我正在开发一个微型HTTP服务器,用于单元测试。代码如下。
为什么body
中有req.on()
值,而res.end()
中没有{1>}值?
复制
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;
答案 0 :(得分:2)
您需要让服务器完成对传入数据的读取。
由于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"}