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');
});
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.