首页 > 解决方案 > 无法访问 HTTP 服务器中的 POST 数据

问题描述

我正在开发一个用于单元测试的小型 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;

标签: node.js

解决方案


您需要让服务器完成读取传入数据。

作为req一个可读流,如果你res.endreq.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"}


推荐阅读