I have bunch of static file, they are named article1, article2 and so on. So I know it worked when I do
app.get('/this-is-my-article-routes', (req, res) => {
res.render('article1');
});
but it's too tedious and has lots of repeated code. I tried this but it doesn't work?
const articleArr = [
'this-is-my-article-routes'
];
for (i = 0; i<9; i++) {
app.get(`/${articleArr[i]}`, (req, res) => {
res.render(`article${i}`);
});
}
Is this even possible? or there's something wrong with my codes?
how about simple solution using query params
app.get('articleArr/:id', (req, res) => {
res.render('article/'+req.params.id);
});
Does your array articleArr contains 10 elements?
I think, the better way to do this would be:
var articleList = [ 'first', 'second', 'third']
app.get('/:article', (req, res) {
var articleName = req.params.article
var index = articleList.indexOf(articleName)
if (index == -1) {
// No Aricle Found
}
res.render(`articles$(index)`)
})
This code will also work fine but it is not the recommended one.
var articleList = ['first', 'second']
articleList.forEach(function(value){
app.get('/'+value, (req, res) => {
res.status(200).json({
value: value
})
})
})