我正在尝试解析 Node js 中的 url。从此代码获取空值。它正在接收路径的值。但不适用于主机或协议(protocol)。
var http = require('http');
var url = require('url');
http.createServer ( function (req,res){
var pathname = url.parse(req.url).pathname;
var protocol = url.parse(req.url).protocol;
var host = url.parse(req.url).host;
console.log("request for " + pathname + " recived.");
console.log("request for " + protocol + " recived.");
console.log("request for " + host + " recived.");
res.writeHead(200,{'Content-Type' : 'text/plain'});
res.write('Hello Client');
res.end();
}).listen(41742);
console.log('Server Running at port 41742');
console.log('Process IS :',process.pid);
最佳答案
HTTP protocol不会将合并的 URL 以一个值的形式传达给 Node 解析。
例如,对 http://yourdomain.com/home
的请求到达:
GET /home HTTP/1.1
Host yourdomain.com
# ... (additional headers)
所以,这些碎片不会都在同一个地方。
您可以从
req.url
中获取的路径和查询字符串,正如您所做的那样——对于上面的示例,它将保存"/home"
。var pathname = url.parse(req.url).pathname;
您可以从
req.headers
获得主机,尽管它并不总是需要一个值。var hostname = req.headers.host || 'your-domain.com';
对于协议(protocol),此值没有标准放置。
您可以使用“How to know if a request is http or https in node.js”中给出的建议来确定
http
和https
。var protocol = req.connection.encrypted ? 'https' : 'http';
或者,尽管它不是标准的,但许多客户端/浏览器会为其提供
X-Forwarded-Proto
header 。
关于javascript - Node js URL解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588396/