Home > database >  Node.js render 404 page when page doesn't exist with params
Node.js render 404 page when page doesn't exist with params

Time:12-17

I am hoping someone can help me, I've looked at some possible solutions but I just don't know where I am going wrong! I am learning so please forgive me if this is something simple.

So the following code works rendering the index.ejs file when going to the home route, and fine when going to an existing page.

app.get(`/`, function (req, res) {
    res.render(`index`);
});

app.get(`/:page`, function (req, res) {
    const page = req.params.page;
    res.render(`${page}`);
});

For example, if I type /main then the main.ejs file is rendered ok.

If I type /asdkjbasfijbs (basically a non-existent page) then I want it to render a 404 page that I already have in the 'views' folder but at the moment it says

Error: Failed to lookup view "asdkjbasfijbs" in views directory "/views"

Here's my full code:

const express = require(`express`);
const https = require(`https`);
const ejs = require(`ejs`);
const app = express();
const port = 3000;

app.set(`view engine`, `ejs`);
app.use(express.urlencoded({ extended: true }));
app.use(express.static(`public`));

app.get(`/`, function (req, res) {
    res.render(`index`);
});

app.get(`/:page`, function (req, res) {
    const page = req.params.page;
    res.render(`${page}`);
});

app.listen(port, function () {
    console.log(`Server started on port ${port}`);
});

Thanks in advance.

I've tried adding the following at the end of my routes:

app.get('*', (req, res) => {
res.status(404).send(`Not Found`);
});

and

app.use(function (req, res, next) {
res.status(404).render(`404`);
});

and

app.use((req, res, next) => {
const err = new httpError(404)
return next(err);
});

CodePudding user response:

According to the docs you should be able to provide a callback, which receives an err or the rendered html

If there is an error send a 404 (or check what the error is and send the respective status code). If there is no error, return the rendered html.

res.render(page, (err, html) => {
  if (err) return res.sendStatus(404);
  res.type('html').send(html);
})

Or you can add a default error handler to your routes

app.use((err, req, res, next) => {
  //check what error happened here ... 
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
  • Related