首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Unirest post请求主体

Unirest post请求主体
EN

Stack Overflow用户
提问于 2020-08-25 01:31:40
回答 1查看 1.1K关注 0票数 0

我希望能够将数据从一台服务器发送到另一台服务器,在同一设备上启动(开始)。我有这个:

代码语言:javascript
复制
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发送了一些数据。如何访问请求中的数据?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-25 01:42:54

您使用Content-Type: 'application/json'发送数据,因此在服务器上,您需要连接的中间件不是用于urlencoded,而是用于json。此外,您不需要单独连接body-parser,因为它包含在express中,并且您可以像这样连接必要的中间件:

服务器:

代码语言:javascript
复制
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'));

客户端:

代码语言:javascript
复制
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);
    });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63565949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档