假设我的示例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。
当前回答
下面的代码对我来说就足够了!
const baseUrl = `${request.protocol}://${request.headers.host}`;
// http://127.0.0.1:3333
其他回答
谢谢大家提供这些信息。这是非常烦人的。
把这个添加到你的代码中,你就再也不用考虑它了:
var app = express();
app.all("*", function (req, res, next) { // runs on ALL requests
req.fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl
next()
})
您还可以在那里执行或设置其他操作,例如将日志记录到控制台。
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;
你可以结合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;
我使用节点包'url' (npm install url)
它的作用是当你打电话的时候
url.parse(req.url, true, true)
它将给你检索url的全部或部分的可能性。更多信息请访问:https://github.com/defunctzombie/node-url
我以以下方式使用它来获取http://www.example.com/中/之后的任何内容作为变量并拉出特定的配置文件(有点像facebook: http://www.facebook.com/username)
var url = require('url');
var urlParts = url.parse(req.url, true, true);
var pathname = urlParts.pathname;
var username = pathname.slice(1);
不过,为了实现这一点,你必须在server.js文件中以这种方式创建路由:
self.routes['/:username'] = require('./routes/users');
这样设置你的路由文件:
router.get('/:username', function(req, res) {
//here comes the url parsing code
}