Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  90] [ 5]  / answers: 1 / hits: 7241  / 11 Years ago, tue, december 31, 2013, 12:00:00

Obviously the typical example of adding routes to express follows something like the following:



var express = require('express');
var app = express();

app.get('/', function(req, res){
res.send('hello world');
});

app.listen(3000);


Clearly, in most cases you know the get route exists before the server begins listening. But what if you want to dynamically create new routes once the server is listening? In other words, I want to do something like the following:



var express = require('express');
var app = express();

app.listen(3000, function () {
app.get('/', function(req, res){
res.send('hello world');
});
});


In practice the callback of the route would obviously be pulled dynamically from some remote source. I've tested the above code and everything appears to function properly, however, I was hoping to get confirmation that there wouldn't be any unintended side-effects of creating routes after app.listen is called before I move forward with this pattern.



Note: To clarify, I don't know what the routes will be when I write the main server.js file that will be creating the express server (hence why I can't create the routes before listen is called). The list of routes (and their respective handlers/callback functions) will be pulled from a database while the server is starting up/running.


More From » node.js

 Answers
3

According to TJ (author of Express), it’s okay to add routes at runtime.



The main gotcha is going to be that routes are evaluated in the order they were added, so routes added at runtime will have a lower precedence than routes added earlier. This may or may not matter, depending on your API design.


[#49109] Monday, December 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leandraannabellar

Total Points: 255
Total Questions: 89
Total Answers: 89

Location: England
Member since Sun, May 21, 2023
1 Year ago
;