假设我的示例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.headers.host + req.url来构造它。当然,如果你是在不同的端口,你得到的想法;-)

其他回答

我的代码是这样的,

params['host_url'] = req.protocol + '://' + 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);
}
const fullUrl = `${protocol}://${host}:${port}${url}`
      
    const responseString = `Full URL is: ${fullUrl}`;                       
    res.send(responseString);  
})

你可以结合req。协议,要求。主机名和req.originalUrl。请注意要求。主机名,而不是请求。Host或req.get(“Host”),这是可行的,但更难阅读。

const completeUrl = `${req.protocol}://${req.hostname}${req.originalUrl}`;

使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>