简体   繁体   中英

Cannot read property 'status' of undefined in Express js

Here is my code:

const db = require('../models');

const findAllUsers = async (req, res) => {
  try {
    const users = await db.User.findAll();
    return res.status(200).json({
      users,
    });
  } catch (error) {
    return res.status(500).json({error: error.message})
  }
}


module.exports = {
  findAllUsers,
}

While executing this am getting an error saying "TypeError: Cannot read property 'status' of undefined"

Am using, express js and sequelize to perform the action !

this is my route

router.get('/users', (req, res) => {
    //const a = controller.allUsers;
    res.send(controller.findAllUsers());
});

TypeError: Cannot read property 'status' of undefined

What are you accessing status on which might be undefined?

 res.status

So what is res and why might be undefined?

 const findAllUsers = async (req, res) => {

res is the second argument you pass to findAllUsers

controller.findAllUsers()

… and you aren't passing any arguments to findAllUsers so they will both be undefined.

You need to pass values to the arguments you use!


Aside:

 res.send(controller.findAllUsers());

You're taking the return value of findAllUsers and sending it in the response … but you're already trying to send a response inside that function. You can't respond multiple times to the same request.

Why don't you try to pass req and res as input parameter to the findAllUsers method?

router.get('/users', (req, res) => {
    controller.findAllUsers(req, res);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM