【问题标题】:Back-end API receiving empty request body when making request from front-end从前端发出请求时,后端 API 接收空请求正文
【发布时间】:2019-05-02 13:16:01
【问题描述】:

我正在本地主机上构建 Web 应用程序。

前端是Reactjs框架,运行在localhost:3000

后端是nodejs + Express,运行在localhost:4000

现在,我创建了下面的 API:

router.post('/register', function (req, res) {
    console.log(req.body); // {}, why it is empty?

    // create new instance, save it to database
    User.create(req.body).then(function () {
        res.send('success');
    });
});

前端部分是:

handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values); // value is not empty, I have tested! So we did send something to the API

                const input = JSON.stringify({
                    username: values.username,
                    password: values.password,
                });

                console.log(input);
                $.ajax({
                    url: `${API_ROOT}/register`,
                    method: 'POST',
                    data: JSON.stringify({
                        username: values.username,
                        password: values.password,
                    }),
                }).then((response) => {
                    if (response === 'success') {
                        this.props.history.push('/login');
                    } else {
                        console.log('do not jump');
                    }

                });
            }
        });
    }

我已经通过邮递员测试了API,我可以将用户添加到MongoDB,所以API很好。

我有我发送给 API 的 console.log,它不是空的,但是,后端 API 接收到空的请求正文。我已经修复了“Access-Control-Allow-Origin”问题,所以我想我确实向 API 发送了一些东西,但是后端 API 收到了空的请求正文。

【问题讨论】:

  • 也许您必须在请求中添加内容类型? headers: { 'Content-Type': 'application/json' }
  • 你试过添加bodyparser中间件router.use(bodyParser.json())吗?
  • @Tholle 你说的太对了!添加表头后,问题解决,谢谢!!!
  • 我的回答对你有用吗?如果是这种情况,请考虑 accepting it

标签: node.js ajax reactjs


【解决方案1】:

如果您添加一个内容类型标头,说明请求的主体是什么类型,它应该可以按预期工作。

$.ajax({
  url: `${API_ROOT}/register`,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  data: JSON.stringify({
    username: values.username,
    password: values.password,
  })
})

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2020-03-04
    • 2012-08-19
    • 2019-07-17
    • 2019-11-10
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2019-09-08
    相关资源
    最近更新 更多