如何使用nodejs请求模块正确发送请求头?

Dio*_*ung 0 json header request node.js

我正在使用requestNodejs模块来发出http请求,但是headers对象存在问题:该值不能包含双引号,否则将以不同方式处理.

基本上我正在调用一个API,它需要headers携带一个属性"X-Accesstoken".

我的代码:

var userId = "123";
var url = "/users/{id}".replace("{id}", userId) ;
var token = "abcd1234"; //changed to protect the innocence, anyway it'll be the valid generated token

var options = {
        method: 'GET',
        url: url,
        header: {
            "x-Accesstoken": token
            "Content-Type": "application/json"
        }
    };
    console.log('testing ' + url);
    request(options, function(error,response,body){
        console.log('body:' + body);
    });
Run Code Online (Sandbox Code Playgroud)

我总是遇到这个错误:

body:'{
  "status": 403,
  "code": 0,
  "reason": "Not authenticated"
}
Run Code Online (Sandbox Code Playgroud)

然后,如果我使用Chrome高级REST API客户端,我意识到这个问题是因为双引号(")中的X-Accesstokenheaders

双引号 - >错误: 双引号,得到错误

没有双引号 - >好的 没有双引号,好的

在这种情况下,如何在没有双引号的情况下发送请求标头?

更新:header错字是根本原因,而不是双引号或大写"X-Accesstoken".当我使用高级REST客户端发送请求时,它将双引号作为标头值的一部分发送,从而使我的令牌无效.