TypeError:无法读取null的属性“会话”

时间:2019-02-24 16:53:45

标签: node.js mongodb session

谁能告诉我代码中的错误是什么。我找不到我的错误_____________________________________________________________________________

router.get('/:filename', (req,res) => {
    const img = req.params.filename; // Filename
    gfs.collection('wdress').findOne({filename: img}, (req,file) => {
        if(req.session.name==null) {
            req.session.name = [{
                brand: img
            }]
        } else {
            req.session.name.push({
                brand: img
            });
        }
    });
});

错误

 TypeError: Cannot read property 'session' of null
  at gfs.collection.findOne (M:\FinalProject\Commerce\routes\index.js:186:8)
 at result 
 (M:\FinalProject\Commerce\node_modules\mongodb\lib\utils.js:414:17)

app.js

app.use(function(req, res, next) {
 res.locals.items = req.session;
 next();
});

1 个答案:

答案 0 :(得分:1)

我猜这个回调

gfs.collection('wdress').findOne({filename: img}, (req,file) => {

应将第一个参数设为error

gfs.collection('wdress').findOne({filename: img}, (error,file) => {

您在回调中获得了error = null,并且req与更高范围req中的另一个(req,res)重叠。看起来这是复制/粘贴错字。