如何使用 express req 对象获取请求路径 [英] how to get request path with express req object
问题描述
我正在使用 express + node.js 并且我有一个 req 对象,浏览器中的请求是/account 但是当我登录 req.path 时,我得到的是 '/' --- 而不是 '/account'.>
I'm using express + node.js and I have a req object, the request in the browser is /account but when I log req.path I get '/' --- not '/account'.
//auth required or redirect
app.use('/account', function(req, res, next) {
console.log(req.path);
if ( !req.session.user ) {
res.redirect('/login?ref='+req.path);
} else {
next();
}
});
req.path 是/什么时候应该是/account ??
req.path is / when it should be /account ??
推荐答案
8 年后更新:
req.path
是 已经在做我在这里提到的完全相同的事情.我不记得这个答案是如何解决问题并被接受为正确答案的,但目前它不是一个有效的答案.请忽略此答案.感谢@mhodges 提到这一点.
req.path
was already doing exactly same thing that I mentioned here. I don't remember how this answer solved issue and accepted as a correct answer but currently it's not a valid answer. Please ignore this answer. Thanks @mhodges for mentioning this.
原答案:
如果你真的只想得到路径"如果没有查询字符串,您可以使用 url
库来解析并获取 url 的路径部分.
If you want to really get only "path" without querystring, you can use url
library to parse and get only path part of url.
var url = require('url');
//auth required or redirect
app.use('/account', function(req, res, next) {
var path = url.parse(req.url).pathname;
if ( !req.session.user ) {
res.redirect('/login?ref='+path);
} else {
next();
}
});
这篇关于如何使用 express req 对象获取请求路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!