Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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');
    });
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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');
});
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!