最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot access 'user' before initialization - Stack Overflow

programmeradmin0浏览0评论

I am new in Mern development, and getting this "Cannot access 'user' before initialization" error in controller file

Controller/user.js

const user = require('../models/user')
exports.signup = (req,res)=>{
   console.log('req.body', req.body);
  const user = new user(req.body);
  user.save((err, user)=>{    
if(err){
    return res.status(400).json({
        err
    })
}
res.json({
    user
})
  })
}

Route/user.js

const express = require('express');
const router = express.Router();

const {signup} = require('../controllers/user');

router.post("/signup", signup);
module.exports = router;

I am new in Mern development, and getting this "Cannot access 'user' before initialization" error in controller file

Controller/user.js

const user = require('../models/user')
exports.signup = (req,res)=>{
   console.log('req.body', req.body);
  const user = new user(req.body);
  user.save((err, user)=>{    
if(err){
    return res.status(400).json({
        err
    })
}
res.json({
    user
})
  })
}

Route/user.js

const express = require('express');
const router = express.Router();

const {signup} = require('../controllers/user');

router.post("/signup", signup);
module.exports = router;
Share Improve this question asked Feb 21, 2022 at 15:32 Supriya KumariSupriya Kumari 1812 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

On line 1 you define a variable named user.

On line 4 you define a different variable also named user in a different scope.

At the other end of line 4 you try to call the value of that variable as a function, but it doesn't have a value yet. Hence the error message.

You intended to call the function in the variable from line 1, but since the one on line 4 shadows it, you are calling that instead.

Don't shadow your variables.

Change the name of one of them.

发布评论

评论列表(0)

  1. 暂无评论