clkhlum02
clkhlum02

Reputation: 57

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

Upvotes: 0

Views: 1393

Answers (4)

Ajay Kushwaha
Ajay Kushwaha

Reputation: 80

I think you are confused between front-end routing and back-end routing, please refer this . They are handled separately, and you are kind of mixing them together.

From what I understood, that you are trying to redirect the user to a 404 custom html error page you can do that like this but in front-end side (ANGULAR).

{path:"**",pathMatch:"full",redirectTo:"/home"}

Also its better to redirect them to "home" page instead of error page for better user experience. 404 custom-error page could be used for different purposes such as network failure, server down ,code break-down(Note: they are also for better user experience.)

In node.js its an endpoint and these APIs are called internally by developers, you get a request either you have the response or you don't, in case you don't you can do something like this

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

If you found this answer useful please accept it

Upvotes: 0

Circuit Planet
Circuit Planet

Reputation: 181

Seems like you just forgot to use the path.join function after importing it ;)

Don't forget to join the dirname( __dirname) with your filename.

const path = require('path');
app.get('*', (req, res)=> {
    res.status(404).sendFile(path.join(__dirname, "/404.html"));
});

use it after all your routes not before them.

if you want to send this file just in case of a get request then this should do it but if you want it for all requests then you should use app.use in place of app.get

Upvotes: 0

kevintechie
kevintechie

Reputation: 1521

Assuming you're using express.js. The Express FAQ answers this question. Look under "How do I handle 404 responses?"

In your case, something like this should work:

app.use(function (req, res, next) {
  res.status(404).sendFile('./pathTo/404.html');
});

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

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.

Upvotes: 1

Related Questions