Node. js implements the routing function _ node. js

Source: Internet
Author: User
This article describes how to implement routing in node. js. As the name suggests, routing means that we have different processing methods for different URLs. This article will teach you how to implement routing in node. js. to implement the routing function in js, you can refer to the beginner Node to find a scene that is completely different from your previous point of view-What is JavaScript in your eyes? Special effects? Or is it just interaction with the client? It can be said that JavaScript was first run in a browser. However, to think like this, the browser only provides a context that defines what JavaScript can do, you can think of a similar enterprise here. An enterprise defines what you can do here, but does not say much about what JavaScript itself can do. In fact, as a complete language, JavaScript can be used in different contexts to reflect different capabilities. The Nodejs mentioned here is actually a context provided, a runtime environment, which allows JavaScript code to be run on the backend (out of the browser environment.

The core of route selection is routing. As the name suggests, routing means that we need to have different processing methods for different URLs, such as processing/start business logic and processing/upload module business; the logic is inconsistent. In reality, the routing process will "end" in the routing module, and the routing module is not a module that truly performs "Action" on requests, otherwise, we will not be able to be well expanded when the application process becomes more complex.

Here we first create a module called requestHandlers and add a placeholder function for each request handler:


The Code is as follows:


Function start (){
Console. log ("Request handler 'start' was called .");

Function sleep (milliSeconds ){
Var startTime = new Date (). getTime ();
While (new Date (). getTime () }
Sleep (10000 );
Return "Hello Start ";
}
Function upload (){
Console. log ("Request handler 'upload' was called .");
Return "Hello Upload ";
}

Exports. start = start;
Exports. upload = upload;

In this way, we can connect the request processing program with the routing module to make the routing "traceable ". Then we decided to pass a series of request handlers through an object, and we needed to inject this object into the router () function in loosely coupled mode. The main file index. js:


The Code is as follows:


Var server = require ("./server ");
Var router = require ("./router ");
Var requestHandlers = require ("./requestHandlers ");

Var handle = {};
Handle ["/"] = requestHandlers. start;
Handle ["/start"] = requestHandlers. start;
Handle ["/upload"] = requestHandlers. upload;

Server. start (router. route, handle );

As shown above, it is easy to map different URLs to the same request handler: you only need to add a key "/" attribute to the object, corresponding to requestHandlers. start. In this way, we can simply configure the/start and/requests to be handled by the start handler. After defining the object, we pass it as an additional parameter to the server. For details, see server. js:

The Code is as follows:


Var http = require ("http ");
Var url = require ("url ");

Function start (route, handle ){
Function onRequest (request, response ){
Var pathname = url. parse (request. url). pathname;
Console. log ("Request for" + pathname + "received .");

Route (handle, pathname );

Response. writeHead (200, {"Content-Type": "text/plain "});
Var content = route (handle, pathname );
Response. write (content );
Response. end ();
}
Http. createServer (onRequest). listen (8888 );
Console. log ("Server has started .");
}
Exports. start = start;

In this way, the handle parameter is added to the start () function, and the handle object is passed to the route () callback function as the first parameter. The following defines route. js:

The Code is as follows:


Function route (handle, pathname ){
Console. log ("About to route a request for" + pathname );
If (typeof handle [pathname] === 'function '){
Return handle [pathname] ();
} Else {
Console. log ("No request handler found for" + pathname );
Return "404 Not Found ";
}
}
Exports. route = route;

With the above Code, we first check whether the request processing program corresponding to the given path exists. If so, we call the corresponding function directly. We can get the request processing function from the passed object in the same way as getting elements from the associated array, that is, the expression like handle [pathname, it is like saying "hi, please help me with this path." The program running effect is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.