2017-09-15 8 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

이 문제는 간단했다 :

당신은 같은 비동기 작업의 콜백에 request(...)를 둘 필요가이 문제를 해결하려면. 요청 헤더의 승인 섹션에 문제가 있습니다. 읽어 줄은 :

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

이 변경되어야합니다

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

Authorization 헤더 소문자를 구분합니다. 그렇지 않으면 액세스가 거부 될 수도 있습니다.

0

이것은 일반적인 비동기 문제입니다. ipAddress을 보내려면 먼저 값이 이미 할당되어 있는지 확인해야합니다. 코드에서

: publicIp.v4()으로

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

일반적으로 비동기 작업 (예를 들어, 오픈 DNS에서 쿼리)이며, code x이 당신의 request(...) 문이 바로 publicIp.v4().then(...) 이후 인 경우 즉, ipAddress = ip; 전에 실행, 그것은 것입니다 ipAddressundefined으로 실행합니다.

어쨌든 request(...) 문이 다른 곳에서 실행 되더라도 잠시 후에 ipAddress이 준비되었음을 보증하지 않습니다 - publicIp.v4().then(...)은 많은 시간을 들일 수 있습니다.

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