假设我的示例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。
当前回答
async function (request, response, next) {
const url = request.rawHeaders[9] + request.originalUrl;
//or
const url = request.headers.host + request.originalUrl;
}
其他回答
你可以像这样在路由中使用这个函数
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)
下面的代码对我来说就足够了!
const baseUrl = `${request.protocol}://${request.headers.host}`;
// http://127.0.0.1:3333
我使用节点包'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
}
我发现它有点PITA,以获得所请求的url。我不敢相信没有更简单的快递方式了。应该是req。requested_url
但我是这样设置的:
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;
用这个,
var url = req.headers.host + '/' + req.url;