假设我的示例URL是
http://example.com/one/two
我说我有以下路线
app.get('/one/two', function (req, res) {
var url = req.url;
}
url的值是/one/two。
如何在Express中获得完整的URL ? 例如,在上面的情况下,我想收到http://example.com/one/two。
假设我的示例URL是
http://example.com/one/two
我说我有以下路线
app.get('/one/two', function (req, res) {
var url = req.url;
}
url的值是/one/two。
如何在Express中获得完整的URL ? 例如,在上面的情况下,我想收到http://example.com/one/two。
当前回答
使req.host /点播。当Express后台代理时,主机名有效必须满足两个条件:
App.set('信任代理','环回');在app.js x - forward - host头必须由你自己在webserver中指定。如。apache, nginx
nginx:
server {
listen myhost:80;
server_name myhost;
location / {
root /path/to/myapp/public;
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://myapp:8080;
}
}
apache:
<VirtualHost myhost:80>
ServerName myhost
DocumentRoot /path/to/myapp/public
ProxyPass / http://myapp:8080/
ProxyPassReverse / http://myapp:8080/
</VirtualHost>
其他回答
我使用节点包'url' (npm install url)
它的作用是当你打电话的时候
url.parse(req.url, true, true)
它将给你检索url的全部或部分的可能性。更多信息请访问:https://github.com/defunctzombie/node-url
我以以下方式使用它来获取http://www.example.com/中/之后的任何内容作为变量并拉出特定的配置文件(有点像facebook: http://www.facebook.com/username)
var url = require('url');
var urlParts = url.parse(req.url, true, true);
var pathname = urlParts.pathname;
var username = pathname.slice(1);
不过,为了实现这一点,你必须在server.js文件中以这种方式创建路由:
self.routes['/:username'] = require('./routes/users');
这样设置你的路由文件:
router.get('/:username', function(req, res) {
//here comes the url parsing code
}
通常我依赖这2个,取决于服务器和代理是否存在:
req.socket.remoteAddress
req.headers.referer
const fullUrl = `${protocol}://${host}:${port}${url}`
const responseString = `Full URL is: ${fullUrl}`;
res.send(responseString);
})
你需要使用req.headers.host + req.url来构造它。当然,如果你是在不同的端口,你得到的想法;-)
你可以从req of express得到完整的url。
function fetchPages(req, res, next) {
let fullUrl = req.headers.host + req.originalUrl;
console.log("full url ==> ",fullUrl);
}