Unirest post 请求正文
Unirest post request body
我希望能够将数据从一台服务器发送到另一台服务器,在同一台设备上启动(开始)。我有这个:
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 发送了一些数据。如何访问请求中的数据?
您正在使用 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);
});
我希望能够将数据从一台服务器发送到另一台服务器,在同一台设备上启动(开始)。我有这个:
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 发送了一些数据。如何访问请求中的数据?
您正在使用 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);
});