最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 3浏览 0评论

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

我使用request模块为Nodejs发出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);
    });

我总是遇到这个错误:

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

然后,如果我使用Chrome Advanced REST API客户端,我意识到问题是因为X-Accesstoken里面的headers中的双引号(“)

双引号 - >错误:

没有双引号 - > OK

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

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

回答如下:

不应该是headers而不是header

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

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

我使用request模块为Nodejs发出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);
    });

我总是遇到这个错误:

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

然后,如果我使用Chrome Advanced REST API客户端,我意识到问题是因为X-Accesstoken里面的headers中的双引号(“)

双引号 - >错误:

没有双引号 - > OK

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

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

回答如下:

不应该是headers而不是header

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

发布评论

评论列表 (0)

  1. 暂无评论