Node 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 + "rn");
console.log("href " + href + "rn");

我用本地主机调用侦听器:8080/测试

我希望看到:

path /test
href /localhost:8080/test

相反,我得到

path /test
href /test

为什么 href 不是完整的网址?

正如@adeneo评论中所说,req.url只包含路径。有两种解决方案,具体取决于您是否使用快递。

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

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

这将输出:

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 + "rn");
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');

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

最新更新