在请求中发送 IP header NPM

Sending IP in the request header NPM

我正在尝试在 HTTPS 请求中将服务器的 IP(在本例中为我的计算机 public IP)发送到另一台服务器以访问其 API。我已经完成了服务器身份验证,并且拥有我的不记名令牌。我正在使用 Express 和 NPM 进行服务器端编程。我得到的 IP 地址如下:

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 地址有关。我在 header 中发送正确吗?

这是一个典型的异步问题。发送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(...);
});

问题很简单。请求的授权部分存在问题 header。该行内容为:

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

应改为:

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

Authorization header 区分大小写。必须大写,否则会被拒绝访问。