我正在尝试运行nodejs
应用。但是,我遇到的问题是每次我尝试运行该应用程序时,都会引发标题中所述的错误:misconfigured csrf
。
这是我的代码:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const csrf = require('csurf');
const flash = require('connect-flash');
const errorController = require('./controllers/error');
const User = require('./models/user');
const MONGODB_PASS = 'PASSWORD_HERE';
const MONGODB_URI = `mongodb+srv://USER_HERE:${MONGODB_PASS}@DB_HOST_HERE/shop?retryWrites=true&w=majority`;
const app = express();
const store = new MongoDBStore({
uri: MONGODB_URI,
collection: 'sessions'
});
const csrfProtection = csrf({cookie: true});
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const authRoutes = require('./routes/auth');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'my secret',
resave: false,
saveUninitialized: false,
store
}));
app.use(csrfProtection);
app.use(flash());
app.use((req, res, next) => {
if (!req.session.user) return next();
User.findById(req.session.user._id).then(user => {
req.user = user;
next();
}).catch(err => {throw err});
});
app.use((req, res, next) => {
res.locals.isAuthenticated = req.session.isLoggedIn;
req.locals.csrfToken = req.csrfToken();
next();
});
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(authRoutes);
app.use(errorController.get404);
mongoose.connect(MONGODB_URI)
.then(result => app.listen(3000)).catch(err => { throw err });
我希望该应用程序能够成功运行,但会抛出错误:misconfigured csrf
。我在做什么错?
注:我严重不知道该写些什么了,所以一直抱怨我需要添加更多细节。我相信我已经提供了足够的说明,标题和代码说明。
您正在使用cookie选项:
const csrfProtection = csrf({cookie: true});
它需要cookie-parser中记载的here软件包:如果将“ cookie”选项设置为非false值,则必须在此模块之前使用cookie解析器。