0

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());
});
1
  • I dont understand the downvotes. OP has provided a sample code. The res object is clearly undefined. You should check what arguments are you passing to the findAllUsers function or check if you already ended the response before. Commented Oct 23, 2020 at 14:09

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think you might also do this: router.get('/users', controller.findAllUsers);
0

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.

2 Comments

whats the solution ? as am a beginner
"You need to pass values to the arguments you use!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.