节点js url.parse-href不返回完整的url

我在node.js中有以下非常简单的代码片断(在Windows 7下运行)

var path = url.parse(req.url, true).pathname; var href = url.parse(req.url, true).href; console.log("path " + path + "\r\n"); console.log("href " + href + "\r\n"); 

我用localhost:8080 / test调用监听器

我期望看到:

 path /test href /localhost:8080/test 

相反,我得到

 path /test href /test 

为什么href不是完整的url?

正如@adeneo在评论中所说, req.url只包含path。 有两种解决scheme,取决于你是否使用快递。

如果使用快递:您需要执行以下操作:

 var href = req.protocol + "://"+ req.get('Host') + req.url; console.log("href " + href + "\r\n"); 

这个输出:

 http://localhost:8080/test 

参考: http : //expressjs.com/4x/api.html#req.get

如果使用节点的http服务器 :使用请求的标题:

 var http = require('http'); http.createServer(function (req, res) { var href = "http://"+ req.headers.host + req.url; console.log("href " + href + "\r\n"); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); 

参考: http : //nodejs.org/api/http.html#http_message_headers