0

I have the following Middleware to protect my get-route.

function isAdmin(req, res, next) {
    if(req.user.role == "admin") {
        return next();
    }
    return res.send(404);
}

Is the way I send the error correct?

And this is my API call:

$scope.users = APIService.query({ route:'users' });

How, can I catch the 404 and do some stuff?

Thanks!

zishe
  • 10,665
  • 12
  • 64
  • 103
nofear87
  • 869
  • 2
  • 12
  • 27

1 Answers1

1

...so, there's a ton of stuff out there that turns up on search engines.

That said, try this as a quick fix that points in one direction you can take:

function isAdmin(req, res, next) {
    if(req.user.role == "admin") {
        return next();
    }
    res.status(404).send('You need to be admin to see this page');
}

There's good stuff on handling 404's at:

The last one also provides examples on handling the error while rendering a template.

Community
  • 1
  • 1
Matthew Bakaitis
  • 11,600
  • 7
  • 43
  • 53
  • Thank you! And how I can handle the error in angular, in my query? – nofear87 Jun 18 '14 at 18:48
  • Dunno. I'm a newbie at Angular but I know enough that you should probably ask a new question about that. because there are a few ways you could be handling the async calls from Angular to node, you should post the code from your angular app in the new question. That will get you the best chances of getting an answer to your second question. – Matthew Bakaitis Jun 18 '14 at 18:50
  • Is the order of middlewares important? For exmaple when i use a middleware to redirect 404 errors. Must they stand at the end? For example: app.get('/api/users', isLoggedIn, isAdmin, isError function(req, res) and what is there position when i place the middleware in app.use? thank you! – nofear87 Jun 20 '14 at 07:46
  • Yes. Middleware will execute in the order it is listed. When you see `(req, res, next)`, calling `next()` tells express to move to the next middleware component in the stack if a response was not sent. This is a reason that some middleware (loggers, parsers, etc) need to be 'at the top' of the app so that they pre-process information before routes/business logic get processes. – Matthew Bakaitis Jun 20 '14 at 14:26