passport.deserializeUser executing a DB (sequelize) command for each HTTP request

▼魔方 西西 提交于 2019-12-09 02:46:23

问题


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:

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Over and over and over!

GET / 200 12ms - 780

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Over and over and over!

GET /js/ui.js 304 4ms

Over and over and over!

GET /stylesheets/main.css 304 6ms

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Over and over and over!

GET /images/logo.jpg 304 3ms

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);
    });
});

The page I'm requesting is:

index: function(req, res) {
    res.render('index', {
        title: "Welcome to EKIPLE!",
        currentUser: req.user
    });
}

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?


回答1:


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.

That way, the requests for static resources will never hit the Passport middleware, so won't result in those unnecessary database-requests.



来源:https://stackoverflow.com/questions/15213484/passport-deserializeuser-executing-a-db-sequelize-command-for-each-http-reques

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!