Sending IP in the request header NPM

640 views Asked by At

I am trying to send the server's IP (in this case, my computers public IP) to another server in a HTTPS request to get access to their API. I have completed the server authentication and I have my bearer token. I am using an Express and NPM for server side programming. I am getting my IP address as follows:

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

I am making my request as follows.

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);
 });
}

I am getting a 401 error. I have done research and I believe its something to do with sending the IP address. Am I sending it correctly in the header?

2

There are 2 answers

0
Christopher Littlewood On BEST ANSWER

The problem was simple. There is an issue in the Authorisation section of the request header. The line that reads:

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

Should be changed to:

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

Authorization header is case sensitive. It needs to be capital otherwise you will be denied access.

0
shaochuancs On

This is a typical async problem. To send ipAddress, you need to guarantee it is already assigned a value first.

In your code:

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

As publicIp.v4() is normally an async operation (query from OpenDNS for example), code x is executed before ipAddress = ip;, which means if your request(...) statement is right after publicIp.v4().then(...), it will be executed with ipAddress as undefined.

Even if request(...) statement is executed somewhere else, some time later, there is no guarantee that ipAddress is ready -- publicIp.v4().then(...) may cost a lot of time.

To fix the issue, you need to put request(...) into the callback of async operation, such as:

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