2011-12-11 23 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