Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Express Return Error Code with Res.Render

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.

like image 620
joshua-anderson Avatar asked May 18 '13 16:05

joshua-anderson


People also ask

What is RES statusCode in Nodejs?

The res. status() function set the HTTP status for the response. It is a chainable alias of Node's response. statusCode. Syntax: res.status( code )

How can you deal with error handling in Express js?

For error handling, we have the next(err) function. A call to this function skips all middleware and matches us to the next error handler for that route. Let us understand this through an example. var express = require('express'); var app = express(); app.


2 Answers

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});
});
like image 106
jmingov Avatar answered Sep 17 '22 15:09

jmingov


I cannot find confirmation in Express docs but using:

res.status(statusCode).render(page)

Status and render the page correctly.

express: "4.17.1"
like image 33
Knautiluz Avatar answered Sep 18 '22 15:09

Knautiluz