2011-12-11 44 views
0

用於學習目的我沒有使用外部模塊,所以我正在嘗試對服務器執行身份驗證請求。它的工作原理與捲曲:如何使用node.js中的身份驗證處理重定向響應?

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

[解決,thansk ...]但在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() 

我試圖請求再次與 '位置'在標題中,但我得到了相同的結果。

感謝您的幫助。

+0

我知道你說你解決了這個已經,但它仍然值得別人答案。 – Marco

回答

1

-u捲曲允許您傳遞驗證標頭的值。在節點中,您可以手動執行此操作。基本身份驗證(我假設你正在使用)的規範說傳遞基於64編碼格式的憑據。在節點中手動執行此操作看起來像這樣。

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

我認爲這樣的頭部名稱是「授權」,當我用節點v.0.4.7(對於heroku)執行此請求時,我得到錯誤,因爲該版本中不存在auth屬性,所以我試着用「授權」標題,工作正常。 –

+0

是的,愚蠢的錯誤。固定。謝謝。 – Marco