HTTP 请求主体为空

HTTP request has empty body

我正在使用 Node 和 Express 创建一个简单的客户端-服务器程序。该程序应该能够在客户端接受 JSON 输入,执行一些逻辑,然后将信息传递给服务器端。

目前我可以成功地向客户端提供输入,但是,服务器端在执行 POST 后输出 request.body 到控制台时只是 returns {}来自客户端。

client.js:

const clientPort = 9300;
const serverPort = 9400;

var express = require('express');
var http = require('http');

var app = express();
app.use(express.json());

// json callback
app.post('/api', function(request, response) {
    console.log(`api callback`);

    // log the received json
    var input = request.body;
    console.log(`Received JSON: ${JSON.stringify(input)}`);

    var options = {
        host: 'localhost',
        port: serverPort,
        path: '/',
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        }
    };

    const httpReq = http.request(options, function(response) {
        response.setEncoding('utf8');
        response.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`);
        });
        response.on('end', () => {
            console.log('No more data in response.');
        });
    });

    // write word to request
    httpReq.write(JSON.stringify(input));
    httpReq.end();

});

// listen on port 9300 for inputs
app.listen(clientPort, 'localhost', () => {
    console.log(`Client listening on port ${clientPort}...`);
});

server.js:

const serverPort = 9400;

var express = require('express');

var app = express();
app.use(express.json());

// expect to receive the JSON input
app.post('/', function(request, response) {
    console.log(`server callback`);
    console.log(JSON.stringify(request.body));

});

// listen on port 9400 for inputs from client
app.listen(serverPort, 'localhost', () => {
    console.log(`Server listening on port ${serverPort}...`);
});

示例输入:

curl --header "Content-Type: application/json" \                                                                                   INT ✘  11s  
--request POST \
--data '{"word":"test"}' \
http://localhost:9300/api

client.js 输出(基于以上输入):

Client listening on port 9300...
api callback
Received JSON: {"word":"test"}

最后,server.js 输出:

Server listening on port 9400...
server callback
{}

您必须使用 express urlencoded 中间件,以便它可以解释您请求中的正文对象。

下面app.use(express.json()); 放下面一行

app.use(express.urlencoded({ extended: true }));

更多信息在这里: https://www.geeksforgeeks.org/express-js-express-urlencoded-function/

我所要做的就是将 var options 中的 header 替换为 headers

我要去打自己的脸