在其他模型中未定义req.user

时间:2019-04-29 11:16:59

标签: node.js express passport.js

我有2个模块

  1. 用户
  2. 博客

我已经实现了使用护照认证进行登录注册的用户。当我尝试在博客模型中使用当前用户数据(req.user)时,结果为“未定义”。

我在下面分享了我的代码

app.js

const express = require('express');
const app =express();
const path = require('path');
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended : false }));
app.use(bodyParser.json());

const Users = require("./routes/Users");
const Blogs = require("./routes/Blog");
app.use("/users",Users);
app.use("/blogs",Blogs);

app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');

app.listen(3000, function() {
  console.log('Server started...');
});

users.js

const passport = require('passport');
const express=require('express');
const users = express.Router();
const models = require('../models');
const User = models.users;

var cookieParser = require('cookie-parser');
const session = require('express-session');

users.use(cookieParser());
users.use(session({
secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));
users.use(passport.initialize());
users.use(passport.session());

require('../config/passport.js')(passport, User); 

users.post('/register',passport.authenticate('local-register', {
        successRedirect: '/users/profile', 
        failureRedirect: '/users/register'
    }
));

users.post('/login',passport.authenticate('local-login', {
        session: true,
        successRedirect: '/users/profile', 
        failureRedirect: '/users/profile'
    }
));

module.exports =users; 

blogs.js

const express = require('express');
const blogs = express.Router();
const blogModel = require('../models/blogs');


blogs.get('/',(req,res) =>{
    console.log(req.user) // RESULTS UNDEFINED
    res.send('Blog List');
});

passport.js

const bCrypt = require('bcryptjs');
const LocalStrategy = require('passport-local').Strategy;

module.exports = function(passport, user) { 
    const User = user;  

    passport.use('local-register', new LocalStrategy( { usernameField: 'email', passwordField: 'password', passReqToCallback: true },  
        function(req, email, password, done) { 
             ... ....

        } 
    ));

    passport.use('local-login', new LocalStrategy({ usernameField: 'email',  passwordField: 'password',   passReqToCallback: true },  
    function(req, email, password, done) {
        .....  .....
    }   
)); 

passport.serializeUser((user, done) => { 
    done(null, user.id); 
});

passport.deserializeUser((id, done) => { 
    const User =user;
    User.findById(id).then((user) =>{ 
        if (user) { 
            done(null, user);
        } else { 
            done(user.errors, null);
         } 
    }); 
}); 
}

2 个答案:

答案 0 :(得分:1)

我相信您的问题是您正在使用快递包裹的多个对象/实例并试图从一个传递到另一个。它不会按预期工作。为了使其正常工作,您应该使用同一Express实例使用多个路由。

答案 1 :(得分:1)

您仅为passport路由器启动req.user(处理Users),这样,只有以/users开头的路由才能真正访问req.user

为了在req.user模块内使用Blogs,您需要为整个passport应用(而不只是用户路由器)启动express

您可能希望将初始化移至app.js文件

app.use(bodyParser.urlencoded({extended : false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());