Node.js 节点jsurl.parse—;href未返回完整的url
我在node.js中有以下非常简单的代码片段(在Windows 7下运行) 我使用localhost:8080/test调用侦听器 我希望看到:Node.js 节点jsurl.parse—;href未返回完整的url,node.js,Node.js,我在node.js中有以下非常简单的代码片段(在Windows 7下运行) 我使用localhost:8080/test调用侦听器 我希望看到: path /test href /localhost:8080/test 相反,我得到了 path /test href /test 为什么href不是完整的url?正如@adeneo在评论中所说,req.url只包含路径。根据您是否使用express,有两种解决方案 如果使用express:您需要执行以下操作: var href = req.pr
path /test
href /localhost:8080/test
相反,我得到了
path /test
href /test
为什么href不是完整的url?正如@adeneo在评论中所说,
req.url
只包含路径。根据您是否使用express,有两种解决方案
如果使用express:您需要执行以下操作:
var href = req.protocol + "://"+ req.get('Host') + req.url;
console.log("href " + href + "\r\n");
此wil输出:
http://localhost:8080/test
参考:
如果使用节点的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');
参考:
req.url
仅包含路径,这就是为什么路由匹配为app.get('/test')
@ChrisG。这是一个伟大的观点,我当然没有注意到。编辑这两种情况的解算。谢谢
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');