PassportJs用户未定义的React前端Express / MongoDB后端

时间:2017-09-14 14:09:19

标签: reactjs express passport.js

我有一个反应前端命中一个仅用于API调用的快速服务器。我使用护照进行身份验证,我遇到了一些问题。我为Facebook设置了策略。我能够使用Facebook登录,调用serialize方法,将用户添加到数据库中,并且我能够在策略回调方法中看到req.user对象,但是,我无法获得req。此后的用户对象。有什么建议吗?

App.js

let express = require('express');
let router = express.Router();
let passport = require('passport');

router.get('/login/facebook', passport.authenticate('facebook', {scope: ["email"]}));

router.get('/facebook/return', 
    passport.authenticate('facebook', { failureRedirect: '/' }),
    (req, res) => {
        res.redirect('http://localhost:3000');
});

router.get('/logout', 
    passport.authenticate('facebook', { failureRedirect: '/' }),
    (req, res) => {
        req.logout();
        res.redirect('http://localhost:3000');
});


module.exports = router;

Auth.js

let express = require('express');
let router = express.Router();
let passport = require('passport');

router.get('/login/facebook', passport.authenticate('facebook', {scope: ["email"]}));

router.get('/facebook/return', 
    passport.authenticate('facebook', { failureRedirect: '/' }),
    (req, res) => {
        res.redirect('http://localhost:3000');
});

router.get('/logout', 
    passport.authenticate('facebook', { failureRedirect: '/' }),
    (req, res) => {
        req.logout();
        res.redirect('http://localhost:3000');
});


module.exports = router;

Species.js

let express = require("express");
let router = express.Router();
let Species = require("../models/species").Species;

router.get('/', 
(req, res, next) => {
    console.log(req.user);
    Species.find({}).exec((err, species) => {
        if(err) return next(err);
        res.json(species);
    });
});

module.exports = router;

1 个答案:

答案 0 :(得分:0)

我的快速小提示

exports.fbauth = passport.authenticate('facebook', {scope: ['email']});
exports.fbcallback = passport.authenticate('facebook', {
    scope: ['email'],
    failureRedirect: '/login',
    failureFlash: 'Failed Login!',
    successRedirect: '/account',
    successFlash: 'You are now logged in!'
});

确保在两种身份验证中都包含范围:电子邮件