Node.js 400 错误请求

标签 node.js mongodb mongoose supertest

当我尝试 POST 到我的 mongo 数据库时,我遇到了 400 bad request,不知道代码出了什么问题。

这是 Mongoose 中的结构:

var exp = mongoose.model('Exp', {
    _creator: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
    },

    exps: [{
        description: {
            type: String,
            required: true
        },
        skillId: {
            type: mongoose.Schema.Types.ObjectId,
            required: true
        }
    }]

});

这是我的测试用例结构,这也是我希望存储数据的方式:

const exp = {
    _creator: UserOneId, // an ObjectID
    exps:[{
        description: "Ate an apple",
        skillId: SkillOneId // an ObjectID
    },{
        description: "Took a shower",
        skillId: SkillTwoId // an ObjectID
    }],

};

exps 部分应该是一个数组,以允许存储多个 exps,每个 exps 都有一个描述和一个技能 ID。

下面是我的 POST 函数:

app.post('/exps', authenticate, (req, res) => {

  var exp = new Exp({
    _creator: req.user._id, // got from suthenticate middleware
    exps: req.body.exps
  });
  exp.save().then(() => {
    res.send(exp);
  }, (e) => {
    res.status(400).send(e);
  });

})

和我的测试用例:

describe('POST /exps', () => {
    it('Should create new exp', (done) => {
        request(app)
            .post('/exps')
            .set('x-auth', users[0].tokens[0].token)
            .send(exps)
            .expect(200)
            .end(done);
    })
});

有了这样的结构,我就是无法弄清楚到底出了什么问题,导致了 400,此处未提及的中间件和变量已通过其他测试用例,所以我认为不是这些。

测试中的错误消息如下所示:

1) POST /exps Should create new exp:
 Error: expected 200 "OK", got 400 "Bad Request"
  at Test._assertStatus (node_modules/supertest/lib/test.js:250:12)
  at Test._assertFunction (node_modules/supertest/lib/test.js:265:11)
  at Test.assert (node_modules/supertest/lib/test.js:153:18)
  at Server.assert (node_modules/supertest/lib/test.js:131:12)
  at emitCloseNT (net.js:1552:8)
  at _combinedTickCallback (internal/process/next_tick.js:77:11)
  at process._tickCallback (internal/process/next_tick.js:104:9)

感谢任何帮助。

最佳答案

啊,找到了。这是 POST 函数中的拼写错误。

关于Node.js 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51888333/

相关文章:

java - 我应该如何设计一个 wordpress 后端 + react + java 前端应用程序?

html - 我想在 Express.js 中渲染静态 html,但仍然有 app.get() 逻辑方法

node.js - nodejs app mongoose数据库where子句与join

node.js - 在express api中返回时,mongoose中_id的类型错误

javascript - NodeJS 与 MongoDB - 实例化 "db"变量的最佳实践

javascript - JSDom 不加载相关脚本

mongodb - MongoDB 中 db.currentOp() 输出中的奇怪操作

mySQL 与复杂实体的树关系

node.js - 在带有 Mongoose (NodeJS) 的 MongoDB 中,如何查询(查找)填充字段?

node.js - 如何查询电子邮件与 example@gmail.com 匹配的嵌套文档的嵌套文档