【问题标题】:TypeError: Cannot read property 'session' of nullTypeError:无法读取 null 的属性“会话”
【发布时间】:2019-02-25 10:24:47
【问题描述】:

谁能告诉我我的代码有什么错误。我找不到我的错误_________________________________________________________________________

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();
});

【问题讨论】:

  • 是的,我已经初始化了那些:

标签: node.js mongodb session


【解决方案1】:

我猜这个回调

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

应该接受第一个参数为error

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

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

【讨论】:

  • 故事的寓意:缩进代码,永远不要复制粘贴。 ;)
猜你喜欢
  • 2020-01-29
  • 2022-01-12
  • 2021-12-04
  • 2021-12-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多