节点:在我无法访问req的函数中访问req.db

时间:2017-06-06 11:16:50

标签: node.js express passport.js passport-facebook

我尝试使用护照将facebook身份验证添加到我的应用中 - 这样做没问题,但我需要访问passport.use()内的数据库。

以下是routes/auth.js中的代码:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

[...]

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email']
    },
    function(accessToken, refreshToken, profile, cb) {
        var db = need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

module.exports = router;

app.js中,我有以下代码:

// make our db accessible to the router
app.use(function(req,res,next) {
    req.db = db;
    next();
});

如何在标记位置的req.db中访问auth.js

1 个答案:

答案 0 :(得分:1)

如果db对象中有req,您可以配置FacebookStrategyreq对象传递给verify函数。

请参阅:

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email'],
        passReqToCallback: true
    },
    function(req, accessToken, refreshToken, profile, cb) {
        var db = req.db; // need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

希望它有效。