NodeJS:错误配置的 csrf

NodeJS: misconfigured csrf

我正在尝试 运行 一个 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 package as documented here如果您将 "cookie" 选项设置为非假值,那么您必须在此模块之前使用 cookie-parser。