假设我的示例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。协议,要求。主机名和req.originalUrl。请注意要求。主机名,而不是请求。Host或req.get(“Host”),这是可行的,但更难阅读。
const completeUrl = `${req.protocol}://${req.hostname}${req.originalUrl}`;
其他回答
你可以结合req。协议,要求。主机名和req.originalUrl。请注意要求。主机名,而不是请求。Host或req.get(“Host”),这是可行的,但更难阅读。
const completeUrl = `${req.protocol}://${req.hostname}${req.originalUrl}`;
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;
const fullUrl = `${protocol}://${host}:${port}${url}`
const responseString = `Full URL is: ${fullUrl}`;
res.send(responseString);
})
谢谢大家提供这些信息。这是非常烦人的。
把这个添加到你的代码中,你就再也不用考虑它了:
var app = express();
app.all("*", function (req, res, next) { // runs on ALL requests
req.fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl
next()
})
您还可以在那里执行或设置其他操作,例如将日志记录到控制台。