How to handle get requests automatically if template exists (using node.js+express)

StackOverflow https://stackoverflow.com/questions/21630249

  •  08-10-2022
  •  | 
  •  

Pergunta

I'm using node.js with express (and EJS as the template language) and would like to know if there is an easy way to automatically handle serving pages matching a given path if a template exists in the template directory.

For example:

app.get('/subdir/:pagename', function(req, res, next) {
    // Automatically & securely load 'pagename' only if 
    // '/subdir/pagename.ejs' exists in my template dir
    res.render(subdir/pagename);
});

I know I could just write a secure handler for this myself by striping everything that isn't A-z0-9-_ from :pagename and then checking if the file exists (and serving a 404 if it doesn't) but curious to know if there is a better way built into node.js than writing some boilerplate to handle it it.

NB: I have static pages served this way already, the only reason these pages are not static are they use the layout system to give them a common header+footer.

Will happily accept "No there isn't." as an answer if there are any Express experts or anyone who's looked into this already!

Foi útil?

Solução

Been using express since the beginning – sorry, the answer is no. TJ did this for good reason as this functionality is specific to your use case and doesn't belong in a framework. You could look to see if anyones written a module in npm for this feature, but as you know, its not very hard to roll your own.

Happy Hacking! =)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top