【问题标题】:Sending a POST request with chai sends an empty body?使用 chai 发送 POST 请求会发送一个空正文?
【发布时间】:2016-11-03 22:29:19
【问题描述】:

我现在有以下设置

test.js

     var user = {
        username: 'test_user',
        email: 'test@test.me',
        password: 'you shall not pass',
        address: 'No where street'
     };
     chai.request(app)
        .post('/api/v1/users')
        .send(user);

我正在我的 routes/user.js 中处理发布请求

router.post('/', function(req, res, next) {
    console.log('body: ' + req.body);
    queries.insertUser(req.body)
        .then(function(id) {
            return queries.getSingleUser(id);
        })
        .then(function(user) {
            res.status(200).json(user);
        })
        .catch(function(err) {
            next(err);
        });
});

req.body 最终是未定义的。任何关于可能出现问题的线索?

代码在https://ide.c9.io/burtonium/node-from-scratch,如果有人想看看的话。

【问题讨论】:

    标签: javascript node.js chai knex.js


    【解决方案1】:

    req.body 未定义通常是由于没有使用 Express 中的 body-parser 中间件,或者声明不正确(例如,要访问 req.body 的路由之后)。

    假设 Chai 发送 JSON,将其添加到您的 Express 应用中:

    app.use(require('body-parser').json());
    

    (在声明路由器之前)

    【讨论】:

    • 作为旁注,chai 报告服务器错误非常无用。有什么办法改变吗?
    • @MathieuBertin 不知道,tbh,我从未使用过chai-http :)
    • 为什么我能够通过简单的 get 请求获得 json?为什么在这种情况下需要 body-parser?
    • @MathieuBertin body-parser 是解析POST 数据(并用它填充req.body)的中间件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2020-11-10
    • 2021-03-12
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多