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.