我希望能够将数据从一台服务器发送到另一台服务器,在同一设备上启动(开始)。我有这个:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlEncodedParser = bodyParser.urlencoded({extended: false});
app.post('/test', urlEncodedParser, (request, response) =>
{
console.log(request.body);
});
app.listen(9999);
console.log('Server started on port 9999');
const unirest = require('unirest');
unirest.post('http://127.0.0.1:9999/test').headers({'Accept': 'application/json', 'Content-Type': 'application/json'}).send({"test1": 123321, "test2": "321123"})
.then((response) =>
{
console.log(response.body);
});这看起来合乎逻辑,但console.log(request.body);提供了空对象{},但在post请求中,我确实使用.send发送了一些数据。如何访问请求中的数据?
发布于 2020-08-25 01:42:54
您使用Content-Type: 'application/json'发送数据,因此在服务器上,您需要连接的中间件不是用于urlencoded,而是用于json。此外,您不需要单独连接body-parser,因为它包含在express中,并且您可以像这样连接必要的中间件:
服务器:
const express = require('express');
const app = express();
app.post('/test', express.json(), (request, response) => {
console.log(request.body);
response.end('OK');
});
app.listen(9999, () => console.log('Server started on port 9999'));客户端:
const unirest = require('unirest');
unirest
.post('http://127.0.0.1:9999/test')
.headers({ Accept: 'application/json', 'Content-Type': 'application/json' })
.send({ test1: 123321, test2: '321123' })
.then((response) => {
console.log(response.body);
});https://stackoverflow.com/questions/63565949
复制相似问题