Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

404 pages using javascript node.js

I am learning how to redirect a user to a 404 page when an ending doesn’t lead to any page. I am stuck on how to redirect the user to the page. I am not sure if I got the URL ending part input wrong or if I got the send file part wrong.

This is what I have tried so far:

    app.get('/:type', (req, res)=> {
    let path = require('path');
    res.status(404).sendFile('404.html');
    });

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you need to handle 404, you might need to add this route at the end of app.js:

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', (req, res) => {
  res.status(404).send('Not Found');
});

Or,

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

If you are using express, it will be handled by it. You can check this link and it has many options almost similar to each other if the above doesn’t work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading