假设我的示例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。
当前回答
我试着把所有数据都记录下来以备不时之需
然后我发现日志rawHeaders和发现所有的数据可用的url
我试了一下
app.post("/news-letter", (req,res) => {
console.log(req.body);
res.redirect(req.rawHeaders[33]);
})
其他回答
你需要使用req.headers.host + req.url来构造它。当然,如果你是在不同的端口,你得到的想法;-)
这里有一个添加函数的好方法,你可以调用req对象来获取url
app.use(function(req, res, next) {
req.getUrl = function() {
return req.protocol + "://" + req.get('host') + req.originalUrl;
}
return next();
});
现在,您有了一个可以在需要时按需调用的函数。
我试着把所有数据都记录下来以备不时之需
然后我发现日志rawHeaders和发现所有的数据可用的url
我试了一下
app.post("/news-letter", (req,res) => {
console.log(req.body);
res.redirect(req.rawHeaders[33]);
})
The protocol is available as req.protocol. docs here Before express 3.0, the protocol you can assume to be http unless you see that req.get('X-Forwarded-Protocol') is set and has the value https, in which case you know that's your protocol The host comes from req.get('host') as Gopal has indicated Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to app.listen at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so req.get('host') returns localhost:3000, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the host header seems to do the right thing regarding the port in the URL. The path comes from req.originalUrl (thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL, originalUrl may or may not be the correct value as compared to req.url.
将这些组合在一起以重建绝对URL。
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
用这个,
var url = req.headers.host + '/' + req.url;