【问题标题】:Node: Accessing req.db in a function where I don't have access to req节点:在我无权访问 req 的函数中访问 req.db
【发布时间】:2017-11-07 09:16:42
【问题描述】:

我正在尝试使用护照将 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();
});

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

【问题讨论】:

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


    【解决方案1】:

    如果dbreq对象中,您可以配置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);
            });
        }
    ));
    

    希望它有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      相关资源
      最近更新 更多