问题描述
我使用 sequelize 作为 ORM 和 passport.js (passport-local) 进行身份验证.我注意到每个 HTTP 请求都会产生一个单独的数据库命令.我开始研究 deserializeUser() 函数.
I'm using sequelize as an ORM and passport.js (passport-local) for authentication. I noticed that every HTTP request is resulting in a separate database command. I started looking at the deserializeUser() function.
加载单个页面时,这是我得到的:
When loading a single page, this is what I get:
执行:SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
一遍又一遍!
GET/200 12ms - 780
GET / 200 12ms - 780
执行:SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
Executing: SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
执行:SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
Executing: SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
一遍又一遍!
GET/js/ui.js 304 4ms
GET /js/ui.js 304 4ms
一遍又一遍!
GET/stylesheets/main.css 304 6ms
GET /stylesheets/main.css 304 6ms
执行:SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
Executing: SELECT * FROM Users
WHERE Users
.id
=1 LIMIT 1;
一遍又一遍!
GET/images/logo.jpg 304 3ms
GET /images/logo.jpg 304 3ms
这是 passport.deserializeUser 的外观:
Here's how passport.deserializeUser looks:
passport.deserializeUser(function(id, done) {
User.find(id).success(function(user) {
console.log('Over and over and over!');
done(null, user);
}).error(function(err) {
done(err, null);
});
});
我请求的页面是:
index: function(req, res) {
res.render('index', {
title: "Welcome to EKIPLE!",
currentUser: req.user
});
}
deserializeUser 是否应该为请求的每个图像、html、css 文件运行?如果是这样,有没有办法减少对数据库的请求数量?
Is the deserializeUser supposed to run for every image, html, css file requested? If so, is there a way of reducing the number of requests to the DB?
推荐答案
这是中间件顺序错误的典型结果.您应该 app.use
(或等效的)处理静态资源的中间件(通常是 express.static
或 connect.static
)在您 app.use
Passport 中间件之前.其他处理不需要通过 Passport 运行的请求的中间件也是如此.
This is a typical result of an incorrect middleware order. You should app.use
(or the equivalent) the middleware which handles static resources (usually express.static
or connect.static
) before you app.use
the Passport middleware. The same goes for other middleware which handle requests that don't require to be run through Passport.
这样,对静态资源的请求永远不会碰到 Passport 中间件,因此不会导致那些不必要的数据库请求.
That way, the requests for static resources will never hit the Passport middleware, so won't result in those unnecessary database-requests.
这篇关于passport.deserializeUser 为每个 HTTP 请求执行 DB(续集)命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!