Home > Enterprise >  Scope of express response
Scope of express response

Time:01-02

I know this is a scope issue, but am not quite sure what I'm missing here.

I have a simple endpoint where, if a user is found I return a simple 'no user found message. Here is the function:

export const getOneUser = (req, res) => {
    const { id } = req.params;
    const foundUser = users.find((user) => user.id == id)
    checkUserExists(foundUser)
    res.send(foundUser)
}

I've replace my standard guard with a helper function. so instead of:

if(!userfound) res.send('No user was found')

with the following function:

const checkUserExists = (x) => {
    if(!x) res.send('No user found')
}

Since I am constantly using this guard I thought this might be a helpful function to write.

The problem is I'm getting the following error, no matter what I do, event if I import { respons } from 'express' and use that:

ReferenceError: res is not defined at checkUserExists (file:///Users/cnak/Desktop/PROJECTS/TEST3/controllers/users.js:7:12) at getOneUser (file:///Users/cnak/Desktop/PROJECTS/TEST3/controllers/users.js:18:5) at Layer.handle [as handle_request] (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/layer.js:95:5) at next (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/layer.js:95:5) at /Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/index.js:281:22 at param (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/index.js:360:14) at param (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/index.js:371:14) at Function.process_params (/Users/cnak/Desktop/PROJECTS/TEST3/node_modules/express/lib/router/index.js:416:3)

How do I create a helper function that can actually pass a response?

I've also tried to return the 'res.send('No user found')

Thanks

CodePudding user response:

Because you are not defining res in your checkUserExists function.

const checkUserExists = (x, res) => {
    if(!x) res.send('No user found')
}

and

...
checkUserExists(foundUser, res);
...

CodePudding user response:

If you are still getting error after sending res in checkUserExists method. Then problem is not here. You need to check your route, that you are passing actual http res instance here or not. Can you please paste your code of index.js and router file.

  • Related