无法访问HTTP服务器中的POST数据

时间:2019-02-01 09:54:49

标签: node.js

我正在开发一个微型HTTP服务器,用于单元测试。代码如下。

为什么body中有req.on()值,而res.end()中没有{}值?

复制

  1. 运行服务器
const WebhookServer = require('./webhook_server');

const server = new WebhookServer();
server.listen();
  1. 运行客户端
$ curl -XPOST http://localhost:1088 -d '{"num":1}'
{"method":"POST","body":"","type":"test"}
  1. 服务器日志
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;

1 个答案:

答案 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"}