Express.js 4-在静态文件之前使用中间件进行身份验证 [英] Express.js 4 - use middleware for authentication before static files
问题描述
在我的express
应用中,我已经设置了要从/public
目录提供服务的静态文件,其内容如下:
In my express
app I've set static files to be served from the /public
directory with this line:
app.use(express.static(__dirname + '/public'));
现在,我需要在提供静态内容之前添加一个用于身份验证的中间件,并且如果未对用户进行身份验证以将其重定向到用于身份验证的路由(例如,/login
).
我不太确定该怎么做.有什么想法吗?
Now I need to add a middleware for authentication before serving the static content and if the user is not authenticated to be redirected to a route for authentication (e.g., /login
).
I'm not really sure how I have to do it. Any ideas?
推荐答案
由于您未指定,因此我假设您已经具有某种身份验证系统.
Since you didn't specify it, I'm going to assume that you already have some kind of authentication system.
在Express中,中间件在代码中的顺序很重要:如果要在中间件2之前执行中间件1,则应将它们相应地放置在代码中.由于express.static
是中间件,因此,如果要在提供静态文件之前进行身份验证,则只需在调用express.static
In Express, the order of the middlewares in the code matters: if you want to have middleware 1 executed before middleware 2, you should place them accordingly in your code. Since express.static
is a middleware, if you want authentication before serving your static files you can simply write your authentication middleware before the call to express.static
app.use(function (req, res, next) {
if (!userAuthenticated(req)) {
return res.redirect('/login');
}
next();
});
app.use(express.static(__dirname + '/public'));
我假设您有一个userAuthenticated
函数,例如,该函数检查HTTP请求是否包含有效的访问令牌.
I am assuming you have a userAuthenticated
function which is for instance checking if the HTTP requests contains a valid access-token.
这篇关于Express.js 4-在静态文件之前使用中间件进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!