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;
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).
By using app.route() method, we can create chainable route handlers for a route path in Express.js.
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.
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.
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 });
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With