2017-09-15 52 views
0

我试图将服务器的IP(在这种情况下,我的计算机公共IP)发送到HTTPS请求中的另一台服务器以访问其API。我已完成服务器身份验证,并拥有我的不记名令牌。我正在使用Express和NPM进行服务器端编程。我得到我的IP地址如下:在请求头中发送IP NPM

var ipAddress; 
publicIp.v4().then(ip => { 
    ipAddress = ip; 
    console.log(ip); 
}); 

我正在提出如下要求。

request({ 

    //Set the request Method: 
    method: 'POST', 
    //Set the headers: 
    headers: { 
    'Content-Type': 'application/json', 
    'Authorization': "bearer "+ token, //Bearer Token 
    'X-Originating-Ip': ipAddress //IP Address 
    }, 
    //Set the URL: 
    url: 'end point url here', 
    //Set the request body: 
    body: JSON.stringify('request body here' 
    }), 
}, function(error, response, body){ 

    //Alert the response body: 
    console.log(body); 
    console.log(response.statusCode); 
}); 
} 

我收到了401错误。我已经完成了研究,我相信它与发送IP地址有关。我是否正确地在标题中发送它?

回答

0

这个问题很简单。请求头的授权部分存在问题。读取的行:

'Authorization': "bearer "+ token, //Bearer Token 

应改为:

'Authorization': "Bearer "+ token, //Bearer Token 

Authorization头是大小写敏感的。它需要是资本,否则你将被拒绝访问。

0

这是一个典型的异步问题。要发送ipAddress,您需要保证它已被首先分配一个值。

在您的代码:

var ipAddress; 
publicIp.v4().then(ip => { 
    ipAddress = ip; 
    console.log(ip); 
}); 
// code x 

作为publicIp.v4()通常是一个异步操作(查询从OpenDNS的例如),code xipAddress = ip;之前执行,这意味着如果您的request(...)语句publicIp.v4().then(...)后右是,这将是以ipAddress作为undefined执行。

即使执行别的地方request(...)声明,一段时间后,有没有保证ipAddress准备 - publicIp.v4().then(...)可能要花很多时间。

为了解决这个问题,你需要把request(...)到异步操作的回调,如:

var ipAddress; 
publicIp.v4().then(ip => { 
    ipAddress = ip; 
    console.log(ip); 
    request(...); 
}); 
相关问题