Nodejs Express Return Error Code with Res.Render
Asked Answered
A

2

15

I am using nodejs with express. I would like to return a custom 404 not found error page. I have it working. however I have not found a solution of how to return a error code with res.render(). I saw a few similar questions but they were old and using deprecated methods. Any help would be greatly appreciated.

Afterdeck answered 18/5, 2013 at 16:15 Comment(0)
V
25

check these:

app.use(function(req, res) {
    res.status(404);
    url = req.url;
    res.render('404.jade', {title: '404: File Not Found', url: url });
});

      // Handle 500
app.use(function(error, req, res, next) {
    res.status(500);
    url = req.url;
    res.render('500.jade', {title:'500: Internal Server Error', error: error, url: url});
});
Virendra answered 18/5, 2013 at 16:41 Comment(0)
S
4

I cannot find confirmation in Express docs but using:

res.status(statusCode).render(page)

Status and render the page correctly.

express: "4.17.1"
Saddlery answered 21/12, 2019 at 17:8 Comment(1)
The Express docs aren't explicit about chaining render, but do state "res.status(code). Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode." expressjs.com/en/api.html#res.statusGent

© 2022 - 2024 — McMap. All rights reserved.