我在 super 测试帖子中发送请求正文时遇到很多麻烦。我已经阅读了其他问题的解决方案,这些问题归咎于主体解析器的配置不当,但这些答案是指自定义数据类型。 (res.body is empty in this test that uses supertest and Node.js)。我像这样配置 body-parser:
var bodyParser = require('body-parser');
app.use(bodyParser.json({ limit: '50mb', type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
我提供的帖子的解决方案说“supertest 使用 this 文件来确定您是否发送 json。”我的内容类型实际上列在那里,所以我不明白为什么这会成为问题。
我正在尝试像这样发布请求:
it ('creates user', function (done) {
var user = {
firstname: 'Joe',
lastname: 'JoeJoe',
email: 'joe@joe.com',
password: 'spartacus',
};
request(app)
.post('/api/users')
.send(user)
.expect(200)
.expect('Sent email to joe@joe.com', done)
});
});
我用这一行导入我的应用程序:
var app = require('../server.js');
server.js 完全配置我的应用程序。 supertest 支持这种应用程序类型吗?有没有办法强制将用户数据作为 req.body 的一部分进行注意?
最佳答案
我相信可以通过将 post
请求中的 content-type
header 设置为 application/vnd.api+json
来解决该问题。您可以在 supertest/superagent 中执行以下操作:
it ('creates user', function (done) {
var user = {
firstname: 'Joe',
lastname: 'JoeJoe',
email: 'joe@joe.com',
password: 'spartacus',
};
request(app)
.post('/api/users')
.set('Content-Type', 'application/vnd.api+json')
.send(user)
.expect(200)
.expect('Sent email to joe@joe.com', done)
});
});
关于json - 使用 application/vnd 的 super 测试请求中的正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476382/