Router for Node.js

I get into Node.JS and want to have flexibility in the routing engine. I want to control the mapping between incoming URLs and what methods are running.

I would really like to configure placeholders in a route suitable for automatic parameter analysis. Sort of

{"routes": [ {'route': {'url': '/path/to/resource/[id]'}, "handler": idHandler()}, {'route': {'url': '/path/to/foo/[category]/bar'}, "handler": fooHandler(), {'route': {'url': '/path/to/resource/'}, "handler": defaultHandler()}} ]}; 
+4
source share
3 answers

You can choose a more specific solution (only for routing), for example Director , or if you do not want to process cookies, sessions, redirection functions, etc. your best option is Express.js or Flatiron (which you can use with the director).

I will insert the code from two so that you can see how they can help with routing:

Express

 app.get('/', function(req, res){ res.send('index page'); }); app.post('/login', function(req, res) { // login logic }); 

director

 // // define a routing table. // var router = new director.http.Router({ '/hello': { get: helloWorld } }); // // You can also do ad-hoc routing, similar to `journey` or `express`. // This can be done with a string or a regexp. // router.get('/bonjour', helloWorld); router.get(/hola/, helloWorld); 

Resources

http://expressjs.com/en/guide/routing.html
http://blog.nodejitsu.com/scaling-isomorphic-javascript-code
http://blog.nodejitsu.com/introducing-flatiron
http://howtonode.org/express-mongodb

+4
source

Yes, express will be your best option, I think. There is no need to "reinvent the wheel", so to speak. You can also use RegEx on routes, giving you plenty of flexibility. I suggest reading in the manual ... he has a lot of good information!

http://expressjs.com/en/guide/routing.html

+2
source

Express.js and Connect have excellent routing support, vhosts and a large number of extensions are available there. For example, simple integration of jade template rendering or less style sheet processing .

Define routes with parameters, regular expressions, and various HTTP methods.

 app.get('/home', function(req, res) { }); app.post('/save/:contactID', function(req, res) { }); app.all('/params/:required/:andOptional?', function(req, res) { }); 

See kickstart and kickstart-example for an example of an expression with jade included and less processing.

0
source

Source: https://habr.com/ru/post/1386801/


All Articles