node.js 向 chai 请求添加自定义 http 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36961197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:09:55  来源:igfitidea点击:

Add custom http headers to chai requests

node.jstestingrequestchai

提问by Trung Tran

I am building an app using node.js and testing with mocha + chai. Is there a way I can add custom headers to my GET and POST chai requests?

我正在使用 node.js 构建一个应用程序并使用 mocha + chai 进行测试。有没有办法可以向我的 GET 和 POST chai 请求添加自定义标头?

For example, I want something like (semi-pseudocode):

例如,我想要类似(半伪代码)的东西:

chai.request(server)
  .get('/api/car/' + data.car_id)
  .headers({'some_custom_attribute':'some_value'})
  .end(function(err, res) {
    //do something
  });

And likewise with post:

和帖子一样:

chai.request(server)
  .post('/api/car/')
  .headers({'some_custom_attribute':'some_value'})
  .send({car_id: 'some_car_id'})
  .end(function(err, res) {
    //do something
  });

Can someone help?

有人可以帮忙吗?

Thanks in advance!

提前致谢!

回答by alexmac

Use setfunction to set http headers:

使用set函数设置 http 标头:

chai.request(server)
  .get('/api/car/' + data.car_id)
  .set('some_custom_attribute', 'some_value')
  .end(function(err, res) {
    //do something
  });

setting-up-requests

设置请求