我正在使用Nodejs中的请求包将发布请求发送到另一台Nodejs服务器:
var options = {
method: 'POST',
url: 'http://12.12.12.12:3230/',
headers: { 'Content-Type': 'application/json' },
body: {
Num:1212,
Cust:'TEST'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
// Process the body and return the response.
// return res.send(body);
});
在另一台Nodejs服务器中:
app.post("/",(req,res)=>{
console.log(req.body.Num)
console.log(`Someone sent a post request`)
})
我正在监听POST请求的第二台Nodejs服务器在控制台中显示以下内容:
undefined
Someone sent a post request
在这种情况下,我如何接收邮寄请求的值?
答案 0 :(得分:1)
确保在您的后端中间件中添加 bodyParser ,例如:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
并要求其位于顶部,例如:
const bodyParser = require('body-parser');
希望这会有所帮助:)
答案 1 :(得分:0)
您需要将主体转换为JSON。
body: JSON.stringify({ Num:1212, Cust:'TEST' }),
答案 2 :(得分:0)
您还需要在诸如express.json()之类的所有路由之上使用主体解析中间件,例如:
app.use(express.json())
答案 3 :(得分:0)
您可以在express中查看bodyParser中间件