Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Okay to add a route to Node.js Express while listening?

Tags:

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.

like image 346
Sanuden Avatar asked Dec 31 '13 13:12

Sanuden


People also ask

Why we use routing in Express JS?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express.

What are the function arguments required to pass to express JS route handlers?

The arguments available to an Express. js route handler function are: req - the request object. res - the response object.

Is Express used for routing?

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths.

CAN node js handle high traffic?

Since Node. js uses non-blocking IO, the server can handle multiple requests without waiting for each one to complete, which means Node. js can handle a much higher volume of web traffic than other more traditional languages.


1 Answers

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.

like image 75
Nate Avatar answered Nov 21 '22 22:11

Nate