In the previous section we integrated the HTTP server (server.js) and the Request routing module (route.js) Together, of course, this is not enough, the route, as the name implies, is that we have different processing methods for different URLs.
Request Handler Module (requesthandlers)
function start () { console.log (' Request handler ' start ' was called. ' );} function upload () { console.log (' Request handler ' upload ' was called. ' == upload;
Here we need to combine the request handler module with the routing module to modify the master file Index.js
var server = require ('./server ' var route = require ('./route ' var requesthandlers = require ('./requesthandlers ') var handler = {};handler[ '/'] = requesthandlers.start;handler[ '/start '] = requesthandlers.start;handler[ '/upload '] = Requesthandlers.upload;server.start (Route.route, handler);
As you can see, it's easy to map different URLs to the same request handler: Simply add a key-to ‘/‘
-property to the object, and requestHandlers.start
we'll be able to configure the clean and concise configuration /start
and /
the request is processed by start
this handler. After we have finished defining the object, we pass it as an additional parameter to the server.
varHTTP = require (' http ');varurl = require (' URL '));functionStart (route, handler) {functiononrequest (Request, response) {varpathname =Url.parse (request.url). Pathname; Console.log (' Request ' + pathname + ' received. '); Route (handler, pathname); Response.writehead (200, { ' Content-type ': ' Text/plain ' }); Response.Write (' Hello node. js '); Response.End (); } http.createserver (ONrequest). Listen (8888); Console.log (' Server has started. ');} Exports.start= start;
This allows us to start()
add parameters to the function handler
and pass the handler
object as the first parameter to the route()
callback function.
function Route (Handler, pathname) { console.log (' route a request for ' + pathname); if (typeof Handler[pathname] = = = ' function ') { handler[pathname] ( ); Else { console.log (' No request handler found for ' + pathname); = route;
In this way, we combine the server, routing, and request handlers. Now that we launch the application and access it in the browser http://localhost:8888/start
, the following log shows that the system called the correct request handler:
/ for/'start'/ for/ for/favicon.ico
"JavaScript" NodeJS (iii)