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

时间:2018-08-20 18:23:45

标签: javascript reactjs session cookies passport.js

我很久以来一直在尝试解决此问题。我已经尝试了所有现有的堆栈溢出类似问题,但是我仍然收到错误。有人可以建议吗?

[尝试但不帮助] 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 个答案:

答案 0 :(得分:0)

得到答案。

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;

我在这里使用了快速会话,但这没什么大不同。