本文介绍了passport.deserializeUser 为每个 HTTP 请求执行一个 DB(sequelize)命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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;

一遍又一遍!

获取/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.staticconnect.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(sequelize)命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 16:11