2011-12-11 5 views
0

学習目的私は外部モジュールを使用していないので、サーバーへの認証要求をしようとしています。それはカールで動作します:node.jsで認証を使用してリダイレクト応答を処理するにはどうすればよいですか?

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

[SOLVED、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のcurlを使用すると、Authenticationヘッダーの値を渡すことができます。ノードでは、これを手動で行います。基本認証の仕様(あなたが使用していると仮定しています)は、基本64エンコード形式の資格情報を渡します。これをノードで手動で行うのは、次のようになります。

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

ヘッダーの名前が "Authorization"だと思うので、ノードv.0.4.7(heroku用)でこのリクエストを実行したときにauthプロパティがそのバージョンに存在しないためにエラーが発生しました。 "Authorization"ヘッダーと正常に動作します。 –

+0

ええ、愚かな間違い。一定。ありがとう。 – Marco

関連する問題