首页 > 解决方案 > NodeJS req.body 始终为空

问题描述

我的 server.js 代码:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Origin', '*');
    next();
});

const AboutController = require('./controllers/AboutController');
app.use('/about', AboutController);

关于Controller.js

router.post('/store', (req, res, next) => {
    // GETTING REQUEST DETAILS AND INITIALIZATION
    let content         = req.body.content;
    let company_name    = req.body.company_name;
    console.log(req.body);
});
module.exports = router;

问题

req.body总是返回{}空对象,我不知道为什么!

我试过的

我试过了console.log(req),它返回了对象,但对象仍然body是空的!

客户端请求

我正在使用 Postman表单数据来模拟客户端请求。

标签: node.jsexpresspostmanbody-parser

解决方案


我找到了解决方案..

我使用的是 Postman,我使用的是表单数据而不是rawjson,它工作得很好,我还不知道为什么!


推荐阅读