node. JS Routing
We want to provide the requested URL and other required GET and POST parameters for the route, and then the route needs to execute the corresponding code based on that data.
All the data we need will be included in the request object, which is passed as the first parameter of the ONrequest () callback function. But in order to parse this data, we need additional node. JS modules, which are URLs and QueryString modules, respectively.
Our servers should be aware of the existence of routes and use them effectively. We can certainly bind this dependency to the server in a hard-coded way, but the programming experience of other languages tells us that this can be very painful, so we will add the routing module loosely using dependency injection.
Server.js File Code:
var http = require ("http"); var url = require ("url"); function Start (route) { function onrequest (request, Response) { var pathname = Url.parse (request.url). Pathname ; Console.log ("Request for" + Pathname + "received."); Route (pathname); Response.writehead ($, {"Content-type": "Text/plain"}); Response.Write ("Hello World"); Response.End (); } Http.createserver (ONrequest). Listen (8888); Console.log ("Server has started."); Exports.start = start;
Router.js File Code:
Function route (pathname) { Console.log ("about-route a request for" + pathname);} Exports.route = route;
Index.js File Code:
var server = require ("./server"), var router = require ("./router"); Server.start (Router.route);
If you start the app now (node Index.js, always remember this command line), then request a URL, you will see the application output the appropriate information, indicating that our HTTP server is already using the routing module, and will pass the requested path to the route:
Run Index:node index.js
node. JS Routing