CJM*_*CJM 5 javascript node.js express
我正在尝试解析节点js中的url。从此代码中获取空值。它正在接收路径的值。但不适用于主机或协议。
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);
Run Code Online (Sandbox Code Playgroud)
HTTP协议不会将组合 URL 传达为一个值以供 Node 解析。
\n\nhttp://yourdomain.com/home例如,对 的请求以以下方式到达:
GET /home HTTP/1.1\nHost yourdomain.com\n# ... (additional headers)\nRun Code Online (Sandbox Code Playgroud)\n\n因此,这些碎片不会都在同一个地方。
\n\n您可以从 中获取路径和查询字符串req.url,就像您在执行 \xe2\x80\x93 时一样,它将适用"/home"于上面的示例。
var pathname = url.parse(req.url).pathname;\nRun Code Online (Sandbox Code Playgroud)您可以从 获取主机req.headers,但并不总是需要值。
var hostname = req.headers.host || \'your-domain.com\';\nRun Code Online (Sandbox Code Playgroud)对于协议,该值没有标准位置。
\n\n您可以使用“如何知道 Node.js 中的请求是 http 还是 https ”中给出的建议来确定http和之间的关系https。
var protocol = req.connection.encrypted ? \'https\' : \'http\';\nRun Code Online (Sandbox Code Playgroud)\n\n或者,尽管它不是标准的,但许多客户端/浏览器会为其提供X-Forwarded-Proto标头。
| 归档时间: |
|
| 查看次数: |
2654 次 |
| 最近记录: |