Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda