2014-02-23 88 views
0

我正在使用request模块为Nodejs发出http请求,但headers对象存在问题:该值不能包含双引号,否则将采用不同的处理方式。如何使用nodejs请求模块正确发送请求标头?

基本上我打电话要求headers携带一个属性“X-Accesstoken”的API。

我的代码:

var userId = "123"; 
var url = "https://stackoverflow.com/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); 
    }); 

我总是得到这个错误:

body:'{ 
    "status": 403, 
    "code": 0, 
    "reason": "Not authenticated" 
} 

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

用双引号 - >错误: with double quotes, got error

没有双引号 - >确定 without double quotes, OK

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

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

+2

1.您如何知道请求模块发送了带双引号的值? 2.你确定这不仅仅是因为你用小写字母“x”拼写了'x-Accesstoken'吗? –

+0

代码中的令牌与您的屏幕截图不匹配。您确定'token' var在发送之前不包含嵌入的引号吗? – Joe

+1

@AndreasHultgren HTTP头名不区分大小写,按照http://www.ietf.org/rfc/rfc2616.txt – Joe

回答

5

是不是应该是headers stedda header

http://nodejs.org/api/http.html#http_http_request_options_callback

+0

@DioPhung如果头是不区分大小写的,那么您可以将其标记为可接受 –

+0

@AndreasHultgren:是的,请求标头不区分大小写,因为@Joe指出,所以这里的根本原因是由于错字'header'(应该是'headers')。这是正确的答案。 –

相关问题