Can routes in Express be declared using a loop?

When I try to declare below, the index page works, and the rest of the pages all 404. I know that this is not a problem with my links.js file, because when I hardcode the output of the for loop, the links all work. I have a console.logged router object and it shows information on the stack. But when I try to open any of the links, they are 404, and nothing is written to the console.

Is it not possible to declare routes using a for loop? The code is copied below.

var express = require('express'); var router = express.Router(); var config = require('../models/config.js'); var links = require('../models/links.js'); // homepage router.get('/', function(req, res, next) { res.render('index', { title: config.title }); }); for (var i = 0; i < links.length; i++) { router.get(links[i].regex, function(req, res, next) { console.log("trying to open " + links[i].url); res.render(links[i].url, { title: links[i].title, link: links[i] }); }); } module.exports = router; 
+5
source share
1 answer

The problem is that you do not have proper closure around the current value of links[i] . By the time your routes are called, i === links.length , so links[i] points to something other than what you expect.

The easiest way is to simply use links.forEach() instead, which creates / uses closure:

 links.forEach(function(link) { router.get(link.regex, function(req, res, next) { console.log("trying to open " + link.url); res.render(link.url, { title: link.title, link: link }); }); }); 
+7
source

Source: https://habr.com/ru/post/1237065/


All Articles