Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can routes in Express be declared with a loop?

When I try to declare the below, the index page works, but the other pages all 404. I know it's not a problem with my links.js file, since when I hard code the output of the for loop, the links all work. I console.logged the router object and it shows the info in the stack. But when I try to open any of the links, they 404, and nothing is logged to the console.

Is it not possible to declare routes using a for loop? 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;
like image 767
jhhayashi Avatar asked Nov 29 '15 19:11

jhhayashi


People also ask

How does Express define routes?

The routes are defined either using . get() or . post() methods on the router object. All the paths are defined using strings (we don't use string patterns or regular expressions).

How is it possible to create Chainable route handlers for a route path in Express JS?

By using app.route() method, we can create chainable route handlers for a route path in Express.js.

How the dynamic routing is working in Expressjs?

To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. var express = require('express'); var app = express(); app. get('/:id', function(req, res){ res.

What is the difference in purpose between a route in react and a route in Express?

Express will handle your backend routes whereas React (with react-router or any front-end routing lib) will handle frontend routes. Your React application will probably be an SPA (single page application), meaning that your server (express or something else) will have to serve the index.


1 Answers

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

The easiest way around this is to simply use links.forEach() instead, which creates/uses a 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 });
  });
});
like image 52
mscdex Avatar answered Sep 16 '22 14:09

mscdex