json - 使用 application/vnd 的 super 测试请求中的正文为空

标签 json node.js express supertest

我在 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/

相关文章:

java - 接收具有相同参数的整数或整数列表

php - 如何检查 MySQL JSON 列是否不包含 laravel 中的值?

Cocoa JSON - 检查数组还是字典

node.js - socket.io 示例 : not working

node.js - 具有不同参数的多个路由,调用相同的资源

node.js - 使用 Express Web 框架的阿拉伯语 URL 路由?

java - NullPointerException 尝试加载文件

javascript - 如何仅更新特定字段并在使用 Mongoose 进行查找和更新时将其他字段保留为以前的值

node.js - Node.js Stream API 的意外行为

angularjs - Angular 不响应 ui-router 的任何路由 - 当我输入时 URL 就消失了