假设我的示例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。


当前回答

通常我依赖这2个,取决于服务器和代理是否存在:

req.socket.remoteAddress

req.headers.referer

其他回答

使用url.format:

var url = require('url');

这支持所有协议,包括端口号。如果你的originalUrl中没有查询字符串,你可以使用这个更干净的解决方案:

var requrl = url.format({
    protocol: req.protocol,
    host: req.get('host'),
    pathname: req.originalUrl,
});

如果你有一个查询字符串:

var urlobj = url.parse(req.originalUrl);
urlobj.protocol = req.protocol;
urlobj.host = req.get('host');
var requrl = url.format(urlobj);

你可以像这样在路由中使用这个函数

app.get('/one/two', function (req, res) {
    const url = getFullUrl(req);
}

/**
 * Gets the self full URL from the request
 * 
 * @param {object} req Request
 * @returns {string} URL
 */
const getFullUrl = (req) => `${req.protocol}://${req.headers.host}${req.originalUrl}`;

要求的事情。Protocol会给出HTTP或https, Req.headers.host会给你完整的主机名,比如www.google.com, 要求的事情。originalUrl会给出剩下的路径名(在你的例子中是/one/two)

async function (request, response, next) {
  const url = request.rawHeaders[9] + request.originalUrl;
  //or
  const url = request.headers.host + request.originalUrl;
}

你需要使用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);
}