无法读取未定义的属性“ isLoggedIn”

时间:2019-03-17 09:06:22

标签: javascript node.js express csrf multer

此代码用于添加产品,然后使用后端中的mongodb添加到购物车和订单以创建pdf。实际上session.isLoggedIn是在auth js中定义的,请检查该代码,但仍在app.js中,它会给出此错误!

app.JS代码

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 multer = require('multer');

const errorController = require('./controllers/error');
const User = require('./models/user');

const MONGODB_URI =
  'mongodb....url';

const app = express();
const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions'
});
const csrfProtection = csrf();

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'images');
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString() + '-' + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === 'image/png' ||
    file.mimetype === 'image/jpg' ||
    file.mimetype === 'image/jpeg'
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

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(
  multer({ storage: fileStorage, fileFilter: fileFilter }).single('image')
);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use(
  session({
    secret: 'my secret',
    resave: false,
    saveUninitialized: false,
    store: store
  })
);
app.use(csrfProtection);
app.use(flash());

app.use((req, res, next) => {
  res.locals.isAuthenticated = req.session.isLoggedIn;
  res.locals.csrfToken = req.csrfToken();
  next();
});

app.use((req, res, next) => {
  // throw new Error('Sync Dummy');
  if (!req.session.user) {
    return next();
  }
  User.findById(req.session.user._id)
    .then(user => {
      if (!user) {
        return next();
      }
      req.user = user;
      next();
    })
    .catch(err => {
      next(new Error(err));
    });
});

app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(authRoutes);

app.get('/500', errorController.get500);

app.use(errorController.get404);

app.use((error, req, res, next) => {
  // res.status(error.httpStatusCode).render(...);
  // res.redirect('/500');
  res.status(500).render('500', {
    pageTitle: 'Error!',
    path: '/500',
    isAuthenticated: req.session.isLoggedIn
  });
});

mongoose
  .connect(MONGODB_URI, { useNewUrlParser: true })
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });

用于控制isAuthenticated的auth.js

const crypto = require('crypto');

const bcrypt = require('bcryptjs');
const nodemailer = require('nodemailer');
const sendgridTransport = require('nodemailer-sendgrid-transport');
const { validationResult } = require('express-validator/check');

const User = require('../models/user');

const transporter = nodemailer.createTransport(
  sendgridTransport({
    auth: {
      api_key:
        'api.........key'
    }
  })
);

exports.getLogin = (req, res, next) => {
  let message = req.flash('error');
  if (message.length > 0) {
    message = message[0];
  } else {
    message = null;
  }
  res.render('auth/login', {
    path: '/login',
    pageTitle: 'Login',
    errorMessage: message,
    oldInput: {
      email: '',
      password: ''
    },
    validationErrors: []
  });
};

exports.getSignup = (req, res, next) => {
  let message = req.flash('error');
  if (message.length > 0) {
    message = message[0];
  } else {
    message = null;
  }
  res.render('auth/signup', {
    path: '/signup',
    pageTitle: 'Signup',
    errorMessage: message,
    oldInput: {
      email: '',
      password: '',
      confirmPassword: ''
    },
    validationErrors: []
  });
};

exports.postLogin = (req, res, next) => {
  const email = req.body.email;
  const password = req.body.password;

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).render('auth/login', {
      path: '/login',
      pageTitle: 'Login',
      errorMessage: errors.array()[0].msg,
      oldInput: {
        email: email,
        password: password
      },
      validationErrors: errors.array()
    });
  }

  User.findOne({ email: email })
    .then(user => {
      if (!user) {
        return res.status(422).render('auth/login', {
          path: '/login',
          pageTitle: 'Login',
          errorMessage: 'Invalid email or password.',
          oldInput: {
            email: email,
            password: password
          },
          validationErrors: []
        });
      }
      bcrypt
        .compare(password, user.password)
        .then(doMatch => {
          if (doMatch) {
            req.session.isLoggedIn = true;
            req.session.user = user;
            return req.session.save(err => {
              console.log(err);
              res.redirect('/');
            });
          }
          return res.status(422).render('auth/login', {
            path: '/login',
            pageTitle: 'Login',
            errorMessage: 'Invalid email or password.',
            oldInput: {
              email: email,
              password: password
            },
            validationErrors: []
          });
        })
        .catch(err => {
          console.log(err);
          res.redirect('/login');
        });
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

exports.postSignup = (req, res, next) => {
  const email = req.body.email;
  const password = req.body.password;

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.array());
    return res.status(422).render('auth/signup', {
      path: '/signup',
      pageTitle: 'Signup',
      errorMessage: errors.array()[0].msg,
      oldInput: {
        email: email,
        password: password,
        confirmPassword: req.body.confirmPassword
      },
      validationErrors: errors.array()
    });
  }

  bcrypt
    .hash(password, 12)
    .then(hashedPassword => {
      const user = new User({
        email: email,
        password: hashedPassword,
        cart: { items: [] }
      });
      return user.save();
    })
    .then(result => {
      res.redirect('/login');
      return transporter.sendMail({
        to: email,
        from: 'shop@node-complete.com',
        subject: 'Signup succeeded!',
        html: '<h1>You successfully signed up!</h1>'
      });
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

exports.postLogout = (req, res, next) => {
  req.session.destroy(err => {
    console.log(err);
    res.redirect('/');
  });
};

exports.getReset = (req, res, next) => {
  let message = req.flash('error');
  if (message.length > 0) {
    message = message[0];
  } else {
    message = null;
  }
  res.render('auth/reset', {
    path: '/reset',
    pageTitle: 'Reset Password',
    errorMessage: message
  });
};

exports.postReset = (req, res, next) => {
  crypto.randomBytes(32, (err, buffer) => {
    if (err) {
      console.log(err);
      return res.redirect('/reset');
    }
    const token = buffer.toString('hex');
    User.findOne({ email: req.body.email })
      .then(user => {
        if (!user) {
          req.flash('error', 'No account with that email found.');
          return res.redirect('/reset');
        }
        user.resetToken = token;
        user.resetTokenExpiration = Date.now() + 3600000;
        return user.save();
      })
      .then(result => {
        res.redirect('/');
        transporter.sendMail({
          to: req.body.email,
          from: 'shop@node-complete.com',
          subject: 'Password reset',
          html: `
            <p>You requested a password reset</p>
            <p>Click this <a href="http://localhost:3000/reset/${token}">link</a> to set a new password.</p>
          `
        });
      })
      .catch(err => {
        const error = new Error(err);
        error.httpStatusCode = 500;
        return next(error);
      });
  });
};

exports.getNewPassword = (req, res, next) => {
  const token = req.params.token;
  User.findOne({ resetToken: token, resetTokenExpiration: { $gt: Date.now() } })
    .then(user => {
      let message = req.flash('error');
      if (message.length > 0) {
        message = message[0];
      } else {
        message = null;
      }
      res.render('auth/new-password', {
        path: '/new-password',
        pageTitle: 'New Password',
        errorMessage: message,
        userId: user._id.toString(),
        passwordToken: token
      });
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

exports.postNewPassword = (req, res, next) => {
  const newPassword = req.body.password;
  const userId = req.body.userId;
  const passwordToken = req.body.passwordToken;
  let resetUser;

  User.findOne({
    resetToken: passwordToken,
    resetTokenExpiration: { $gt: Date.now() },
    _id: userId
  })
    .then(user => {
      resetUser = user;
      return bcrypt.hash(newPassword, 12);
    })
    .then(hashedPassword => {
      resetUser.password = hashedPassword;
      resetUser.resetToken = undefined;
      resetUser.resetTokenExpiration = undefined;
      return resetUser.save();
    })
    .then(result => {
      res.redirect('/login');
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

控制台错误:-

TypeError: Cannot read property 'isLoggedIn' of undefined
    at app.use (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\app.js:92:34)
    at Layer.handle_error (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:315:13)
    at D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:275:10)
    at Layer.handle_error (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\layer.js:67:12)
    at trim_prefix (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:315:13)
    at D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:275:10)
    at Layer.handle_error (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\layer.js:67:12)
    at trim_prefix (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:315:13)
    at D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Udemy Courses\Node Js\19 Error Handling\04-status-codes\node_modules\express\lib\router\index.js:275:10)

我试图通过在LoggedIn中分配值来编辑代码,但是它给出了未定义crsf代码的错误,请帮助提供有关此代码的信息,因为很多时候它仍然给出相同的错误,因此我正在尝试解决该错误。

代码运行得非常好,在我将multer包添加到节点应用程序以进行文件上传后,抛出了此错误,现在此错误不再发生。

3 个答案:

答案 0 :(得分:1)

我也按照他的教程进行操作,并遇到了这个问题,还检查了它的根源是Express错误处理还是multer。经过四个小时的调试和谷歌搜索,这是我找到的解决方案:

  

https://stackoverflow.com/a/48653921/11330560

这:

  

https://github.com/expressjs/multer/issues/513#issuecomment-422573221

基本上,Windows OS文件不接受以“:”命名的文件。他使用Mac OS。 因此您必须在.replace(/:/g, '-')前面添加new Date().toISOString(),即

  

新Date()。toISOString() .replace(/:/ g,'-')

我希望它也能解决您的问题:)

答案 1 :(得分:1)

我也遇到过同样的问题,对此的答案在课程的“常见问题”部分中给出。如果您仍然没有收到,请按照以下步骤操作。

使用npm install --save uuid
安装uuid软件包 要求使用:const { v4: uuidv4 } = require('uuid')

将代码重写为:

const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images');
},
 filename: (req, file, cb) => {
cb(null, uuidv4() + '-' + file.originalname);
}
});

我希望这也能解决您的问题。 谢谢:)

答案 2 :(得分:1)

为此使用uuid而不是newDate().toIsoString()

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'images');
    },
    filename: (req, file, cb) => {
        cb(null, uuidv4() + '-' + file.originalname);
    }
});