[英]Get My Web App Base URL in JavaScript
您必须连接'url'模块
var http = require('http');
var url = require('url') ;
http.createServer(function (req, res) {
var hostname = req.headers.host; // hostname = 'localhost:8080'
var pathname = url.parse(req.url).pathname; // pathname = '/MyApp'
console.log('http://' + hostname + pathname);
res.writeHead(200);
res.end();
}).listen(8080);
UPD:
在Node.js v8 url模块中获取用于处理URL的新API。 见文档 :
注意:虽然旧版API尚未弃用,但它仅用于向后兼容现有应用程序。 新的应用程序代码应该使用WHATWG API。
用于获取节点应用程序中的URL详细信息。 您必须使用URL模块。 URL模块会将您的网址拆分为可读部分
以下我给出了代码
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'`enter code here`
要了解有关URL模块的更多信息,请访问https://nodejs.org/api/url.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.