2011-12-11 3 views
0

학습 목적 외부 모듈을 사용하지 않아서 서버에 인증 요청을하려고합니다. '위치'다시 내가 요청하려고node.js에서 인증을 사용하여 리디렉션 응답을 처리하는 방법은 무엇입니까?

var http = require("http"); 
var options = { 
    hostname : 'webpage', 
    port : '80', 
    path : '/email', 
    method : 'GET', 
    headers : { 
     "Connection" : "keep-alive", 
     "User-Agent" : "Mozilla/5.0 (X11; Linux x86_64)" 
    }, 
    auth : "username:password" 
} 

options.agent = new http.Agent(options); 

var req = http.request(options, function(res) { 
// The authentication works fine, like curl without -L parameter 
// STATUS 302 
res.setEncoding('utf8'); 
res.on('data',function(chunk){ 
    console.log(chunk); 

// SOLVED ! 

    var opts = { 
    host : 'webpage', 
    port : '80', 
    path : '/email/', 
    location : res.headers.location, 
    auth : "user:password" 
} 

var require = http.request(opts,function(resp){ 
    resp.setEnconding("utf8"); 
    resp.on('data',function(chk){ 
    console.log(chk); 
    }); 
}); 

require.end(); 
// -------------- 

    // I got the same without -L parameter in curl 
    // <head><title>Document Moved</title></head> 
    // <body><h1>Object Moved</h1>This document may be found <a href="http://webpage/email/">here</a></body> <-- The 'Location' is the same 

}); 
}); 

req.on('error',function(e){ 
console.log('Problem with request : ' + e.message); 
} 

req.end() 

:

curl -L -u user:password http://webpage/email 

[SOLVED, thansk ...]하지만 문제가 Node.js를,이 내 코드입니다 : 그것은 컬와 함께 작동 헤더에 있지만 같은 결과가 나타납니다.

도움 주셔서 감사합니다.

+0

나는 당신이 이미 이것을 풀 었다고 알고 있지만, 여전히 다른 사람들에게 대답 할 가치가있다. – Marco

답변

1

-u in curl을 사용하면 인증 헤더의 값을 전달할 수 있습니다. 노드에서이 작업을 수동으로 수행합니다. 기본 인증을위한 사양 (당신이 사용하고 있다고 가정)은 기본 64 인코딩 형식의 자격 증명을 전달한다고 말합니다. 이것을 노드에서 수동으로 수행하는 것은 다음과 같습니다.

headers = { 
    'Authorization': 'Basic ' + (new Buffer(user + ':' + pass)).toString('base64') 
} 
+0

헤더의 이름이 "Authorization"이라고 생각하기 때문에 노드 v.0.4.7 (heroku 용)에서이 요청을했을 때 auth 속성이 해당 버전에 존재하지 않으므로 오류가 발생했습니다. "Authorization"헤더와 제대로 작동합니다. –

+0

예, 어리석은 실수. 결정된. 감사. – Marco

관련 문제