假设我的示例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。
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;
我发现它有点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;
你可以使用node.js API来获取url,并将来自express的信息传递给URL.format(),而不是自己将这些东西连接在一起。
例子:
var url = require('url');
function fullUrl(req) {
return url.format({
protocol: req.protocol,
host: req.get('host'),
pathname: req.originalUrl
});
}
我的代码是这样的,
params['host_url'] = req.protocol + '://' + req.headers.host + req.url;
我建议使用originalUrl而不是URL:
var url = req.protocol + '://' + req.get('host') + req.originalUrl;
查看originalUrl的描述: http://expressjs.com/api.html#req.originalUrl
在我们的系统中,我们这样做,所以originalUrl对我们很重要:
foo = express();
express().use('/foo', foo);
foo.use(require('/foo/blah_controller'));
Blah_controller是这样的:
controller = express();
module.exports = controller;
controller.get('/bar/:barparam', function(req, res) { /* handler code */ });
我们的url有这样的格式
www.example.com/foo/bar/:barparam
因此,我们需要req。originalUrl在bar控制器的获取处理程序。
这里有一个添加函数的好方法,你可以调用req对象来获取url
app.use(function(req, res, next) {
req.getUrl = function() {
return req.protocol + "://" + req.get('host') + req.originalUrl;
}
return next();
});
现在,您有了一个可以在需要时按需调用的函数。
我使用节点包'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
}
使用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);
使req.host /点播。当Express后台代理时,主机名有效必须满足两个条件:
App.set('信任代理','环回');在app.js x - forward - host头必须由你自己在webserver中指定。如。apache, nginx
nginx:
server {
listen myhost:80;
server_name myhost;
location / {
root /path/to/myapp/public;
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://myapp:8080;
}
}
apache:
<VirtualHost myhost:80>
ServerName myhost
DocumentRoot /path/to/myapp/public
ProxyPass / http://myapp:8080/
ProxyPassReverse / http://myapp:8080/
</VirtualHost>
var full_address = req.protocol + "://" + req.headers.host + req.originalUrl;
or
var full_address = req.protocol + "://" + req.headers.host + req.baseUrl;
谢谢大家提供这些信息。这是非常烦人的。
把这个添加到你的代码中,你就再也不用考虑它了:
var app = express();
app.all("*", function (req, res, next) { // runs on ALL requests
req.fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl
next()
})
您还可以在那里执行或设置其他操作,例如将日志记录到控制台。
你可以像这样在路由中使用这个函数
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
async function (request, response, next) {
const url = request.rawHeaders[9] + request.originalUrl;
//or
const url = request.headers.host + request.originalUrl;
}
2021年
上面的答案工作得很好,但不是首选的文档,因为url。解析现在是遗留的,所以我建议你使用新的URL()函数,如果你想获得更多的控制URL。
表达方式
您可以从下面的代码获得完整的URL。
`${req.protocol}://${req.get('host')}${req.originalUrl}`
示例URL: http://localhost:5000/a/b/c?d=true&e=true#f=false
固定属性(你将在所有路线上得到相同的结果)
req.protocol: http
req.hostname: localhost
req.get('Host'): localhost:5000
req.originalUrl: /a/b/c?d=true&e=true
req.query: { d: 'true', e: 'true' }
非固定属性(将在每条路由中改变,因为它由express自己控制)
路线:/
req.baseUrl: <blank>
req.url: /a/b/c?d=true&e=true
req.path: /a/b/c
路线/
req.baseUrl: /a
req.url: /b/c?d=true&e=true
req.path: /b/c
文档:http://expressjs.com/en/api.html req.baseUrl
URL封装方式
在URL函数中,您将在每个路由中得到相同的结果,因此属性总是固定的。
属性
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
console.log(url)
您将得到如下结果。我根据图像改变了属性的顺序,这样它就可以匹配图像流。
URL {
href: 'http://localhost:5000/a/b/c?d=true&e=true',
protocol: 'http:',
username: '',
password: '',
hostname: 'localhost',
port: '5000',
host: 'localhost:5000',
origin: 'http://localhost:5000',
pathname: '/a/b/c',
search: '?d=true&e=true',
searchParams: URLSearchParams { 'd' => 'true', 'e' => 'true' },
hash: ''
}
注意:散列不能发送到服务器,因为它在服务器中被视为片段,但你会在客户端浏览器中获得。
文档:https://nodejs.org/api/url.html url_new_url_input_base
const fullUrl = `${protocol}://${host}:${port}${url}`
const responseString = `Full URL is: ${fullUrl}`;
res.send(responseString);
})
你可以结合req。协议,要求。主机名和req.originalUrl。请注意要求。主机名,而不是请求。Host或req.get(“Host”),这是可行的,但更难阅读。
const completeUrl = `${req.protocol}://${req.hostname}${req.originalUrl}`;
你可以从req of express得到完整的url。
function fetchPages(req, res, next) {
let fullUrl = req.headers.host + req.originalUrl;
console.log("full url ==> ",fullUrl);
}
我试着把所有数据都记录下来以备不时之需
然后我发现日志rawHeaders和发现所有的数据可用的url
我试了一下
app.post("/news-letter", (req,res) => {
console.log(req.body);
res.redirect(req.rawHeaders[33]);
})