假设我的示例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。
当前回答
var full_address = req.protocol + "://" + req.headers.host + req.originalUrl;
or
var full_address = req.protocol + "://" + req.headers.host + req.baseUrl;
其他回答
用这个,
var url = req.headers.host + '/' + req.url;
使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>
var full_address = req.protocol + "://" + req.headers.host + req.originalUrl;
or
var full_address = req.protocol + "://" + req.headers.host + req.baseUrl;
我发现它有点PITA,以获得所请求的url。我不敢相信没有更简单的快递方式了。应该是req。requested_url
但我是这样设置的:
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;
下面的代码对我来说就足够了!
const baseUrl = `${request.protocol}://${request.headers.host}`;
// http://127.0.0.1:3333