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

284
Visualizações
express.js - single routing handler for multiple routes

I'm currently building an app and I have a routes file that looks like this.

const router = require('express').Router();

router.get('/', (req, res) => res.render('statics/home'));
router.get('/jobs', (req, res) => res.render('statics/jobs'));
router.get('/about-page', (req, res) => res.render('statics/about-page'));
router.get('/valves', (req, res) => res.render('statics/valves'));

router.all('*', (req, res) => res.notFound());

module.exports = router;

I am trying to figure out a way to refactor my routes and have a single route that accepts any string and then checks to see if a file exists matching it

Any help appreciated!

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

To easily handle static file, you can use express static, express will automatic route all file inside static folder

app = require('express')();
app.use('statics',express.static('statics'));
about 4 years ago · Santiago Trujillo Relatório

0

Something like this could work:

const router = require('express').Router();
const fs = require('fs');

router.get(':template', (req, res) => {
  const tpl = req.param('template');
  if (tpl) {
    if (fs.existsSync('/path/to/templates/' + tpl + '.ext')) { // adjust the path and template extension
      res.render('statics/' + tpl);
    } else {
      res.notFound();
    }
  } else {
    res.render('statics/home');
  }
});

router.all('*', (req, res) => res.notFound());

module.exports = router;

Or probably better approach would be to read the templates directory once and create routes based on its contents:

const router = require('express').Router();
const fs = require('fs');

const templates = fs.readdirSync('/path/to/templates');
templates.forEach(tpl => {
  tpl = tpl.substring(tpl.lastIndexOf('/') + 1);
  if (tpl === 'home') {
    router.get('/', (req, res) => res.render('statics/home'))
  } else {
    router.get('/' + tpl, (req, res) => res.render('statics/' + tpl))
  }
});

router.all('*', (req, res) => res.notFound());

module.exports = router;
about 4 years ago · Santiago Trujillo 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