2014-10-01 32 views
0

我需要獲取瀏覽器從url發送到我的node.js應用程序的用戶名和密碼。如何從node.js中的url讀取用戶名和密碼?

我通過各種文檔和對象進行挖掘,但找不到任何有用的東西。有誰知道如何做到這一點?使用身份驗證標題不是一種選擇,因爲現代的運營商不設置它們。

https://username:[email protected]/ 
     ================= 
//   /\ 
//   || 
// I need this part 

感謝您的幫助!

回答

0

這正是你要找的東西:

http://nodejs.org/api/url.html

如果你想知道從哪裏,它在request對象傳遞,也被稱爲「路徑」獲取URL本身:

Node.js: get path from the request

+0

謝謝您的回答。但我需要知道從哪裏獲得完整的url,以將其傳遞給url.format()函數。 – Stephan 2014-10-03 20:02:11

+0

然後你不看如何獲得用戶名/密碼,你正在尋找基本的URL?只要將它從請求對象中取出:req.url – Organiccat 2014-10-04 21:04:35

+0

req.url只包含fqdn之後的路徑(至少當我在localhost上測試時)。 – Stephan 2014-10-07 07:22:44

1

的用戶名:密碼包含在授權報頭作爲base64編碼串:

http.createServer(function(req, res) { 
    var header = req.headers['authorization'] || '',  // get the header 
     token = header.split(/\s+/).pop()||'',   // and the encoded auth token 
     auth = new Buffer(token, 'base64').toString(), // convert from base64 
     parts=auth.split(/:/),       // split on colon 
     username=parts[0], 
     password=parts[1]; 

    res.writeHead(200,{'Content-Type':'text/plain'}); 
    res.end('username is "'+username+'" and password is "'+password+'"'); 

}).listen(1337,'127.0.0.1'); 

看到這個帖子:Basic HTTP authentication in Node.JS?

+0

謝謝你的回答,但不幸的是這對我不起作用。它適用於使用curl而不適用於Chrome(v37)或Firefox(v32)的應用程序。瀏覽器不會將信息轉換爲授權標題。 – Stephan 2014-10-03 19:58:40

0

的URL是在請求對象的服務器訪問:

http.createServer(function(req, res) { 
    var url = req.url 
    console.log(url) //echoes https://username:[email protected]/ 
    //do something with url 
}).listen(8081,'127.0.0.1'); 
+1

這隻在控制檯中顯示「/」,它不包含fqdn,用戶名或密碼。 – Stephan 2014-10-06 07:51:02

相關問題