解决错误:passport.initialize() 中间件未使用

Posted

技术标签:

【中文标题】解决错误:passport.initialize() 中间件未使用【英文标题】:Resolve error: passport.initialize() middleware not in use 【发布时间】:2019-01-26 22:13:33 【问题描述】:

我已经尝试解决这个问题很长时间了。我已经尝试了所有现有的堆栈溢出类似问题,但我仍然收到错误消息。任何人都可以提出一些建议吗?

[试过这个但没有帮助] passport.js passport.initialize() middleware not in use

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport')
const cookieSession = require('cookie-session')


// const assert = require('assert');

const keys = require('./api/middleware/keys')
const passportSetup = require('./api/middleware/passport-setup')
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders');
const userRoutes = require('./api/routes/user')
const oauth = require('./api/routes/oauth')

mongoose.connect('mongodb://node-shop:' + process.env.MONGO_ATLAS_PWD + '@cluster0-shard-00-00-zweme.mongodb.net:27017,cluster0-shard-00-01-zweme.mongodb.net:27017,cluster0-shard-00-02-zweme.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true', 
    useNewUrlParser: true
).then(() => console.log('Mongodb connected and running..')).catch((e) => console.error(e));

mongoose.Promise = global.Promise;
app.set('views', __dirname + '/api/views')
app.set('view engine', 'ejs')
app.use(morgan('dev'));
app.use('/uploads', express.static('uploads'))
app.use(bodyParser.urlencoded(
    extended: false
));
app.use(bodyParser.json());


// to prevent CORS error
app.use((req, res, next) => 
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type,Accept,Authorization');
    if (req.method === 'OPTIONS') 
        res.header('Access-Control-Allow-Methods', 'PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json();
    
    next();
)


app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
app.use('/user', userRoutes)
app.use('/auth', oauth)
app.get('/', (req, res, next) => 
    res.render('index')
)

app.use(cookieSession(
    // name: "session",
    maxAge: 24 * 60 * 60 * 1000,
    keys: [keys.session.cookieKey]
))

//init passport




app.use((req, res, next) => 
    const error = new Error('Not Found');
    error.status = 404;
    next(error);
)

app.use((error, req, res, next) => 
    res.status(error.status || 500)
    res.json(
        error: 
            message: error.message
        
    )

)

app.use(passport.initialize())
app.use(passport.session())

module.exports = app;

【问题讨论】:

【参考方案1】:

得到了答案。

https://github.com/jaredhanson/passport/issues/14#issuecomment-217605461

按照中间件的顺序,我的文件应该是这样的。

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport')
const expressSession = require('express-session')



// const assert = require('assert');

const keys = require('./api/middleware/keys')
const passportSetup = require('./api/middleware/passport-setup')
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders');
const userRoutes = require('./api/routes/user')
const oauth = require('./api/routes/oauth')

mongoose.connect('mongodb://node-shop:' + process.env.MONGO_ATLAS_PWD + '@cluster0-shard-00-00-zweme.mongodb.net:27017,cluster0-shard-00-01-zweme.mongodb.net:27017,cluster0-shard-00-02-zweme.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true', 
    useNewUrlParser: true
).then(() => console.log('Mongodb connected and running..')).catch((e) => console.error(e));

app.use(expressSession(
    // name: "session",
    maxAge: 24 * 60 * 60 * 1000,
    secret: keys.session.cookieKey,
    resave: false,
    saveUninitialized: true,
    cookie: secure: true

))
app.use(passport.initialize())
app.use(passport.session())

mongoose.Promise = global.Promise;
app.set('view engine', 'ejs')
app.set('views', __dirname + '/api/views')
app.use(morgan('dev'));
app.use('/uploads', express.static('uploads'))
app.use(bodyParser.urlencoded(
    extended: false
));
app.use(bodyParser.json());


// to prevent CORS error
app.use((req, res, next) => 
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type,Accept,Authorization');
    if (req.method === 'OPTIONS') 
        res.header('Access-Control-Allow-Methods', 'PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json();
    
    next();
)


app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
app.use('/user', userRoutes)
app.use('/auth', oauth)
app.get('/', (req, res, next) => 
    res.render('index')
)



//init passport



app.use((req, res, next) => 
    const error = new Error('Not Found');
    error.status = 404;
    next(error);
)

app.use((error, req, res, next) => 
    res.status(error.status || 500)
    res.json(
        error: 
            message: error.message
        
    )
    
)

module.exports = app;

这里我使用了 express-session,但差别不大。

【讨论】:

以上是关于解决错误:passport.initialize() 中间件未使用的主要内容,如果未能解决你的问题,请参考以下文章

passport.initialize() 中间件未使用

什么是passport.initialize()? (nodejs快递)

Google oauth20 的 Passport,未使用中间件,passport.initialize()

NodeJS Passport按路由配置,作为中间件添加并且没有错误但它不起作用/触发

护照认证回调挂起

护照中间件不运行