node. JS Routing

Source: Internet
Author: User

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.

Therefore, we need to look at the HTTP request and extract the requested URL and the Get/post parameter from it. Whether this feature should belong to a routing or server (or even as a function of a module itself) is really worth exploring, but here it is tentatively the function of our HTTP server.

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.

wr..Parse(String).Query|wr..Parse(String).Pathname| | | | | ------ -------------------http: Localhost:8888/start?foo=bar&hello=world --- ----- ||  ||  Querystring (string) [ "foo" ] ||  Querystring (string) [ "Hello"                

Of course, we can also use the QueryString module to parse the parameters in the POST request body, there will be a demo later.

Now let's add some logic to the onrequest () function to find the URL path to the browser request:

Varhttp= Require("http");Varwr.= Require("url");functionStart() { functionONrequest(Request,Response) { VarPathname=wr..Parse(Request.wr.).Pathname;Console.Log("Request for" +Pathname+ "Received.");Response.Writehead(200, {"Content-type": "Text/plain"});Response.write ( "Hello World" .} Http.onrequest8888 Consolelog ( "Server has started." }exports. Start = Start        

Well, our app can now differentiate between requests by the URL path of the request-which allows us to use the route (not yet completed) to map the request to the handler using the URL path as a baseline.

In the application we are building, this means that requests from/start and/upload can be handled using different code. We'll see how these things are integrated later.

Now we can write the route, create a file named router.js , add the following:

function Route(pathname){ console.  Log("About to route a request for"+ pathname);} exports.  = route;                  

As you can see, this code doesn't do anything, but for now it's supposed to be. Before adding more logic, let's take a look at how to integrate the routing and the server together.

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.

First, let's extend the server's start () function to pass the route function as a parameter, and theserver.js file code is as follows

Varhttp= Require("http");VarUrl= Require("url");functionStart(Route) { functionONrequest(Request,Response) { VarPathname=Url.Parse(Request.Url).Pathname;Console.Log("Request for" +Pathname+ "Received.");Route(Pathname);Response.Writehead(200, {"Content-type": "Text/plain"});Response.write ( "Hello World" .} Http.onrequest8888 Consolelog ( "Server has started." }exports. Start = Start        

At the same time, we will extend the index.js accordingly so that the routing function can be injected into the server:

var=require("./server");  var=require("./router");  Server.  Start(router.  Route);                  

Here, the functions we pass are still not doing anything.

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:

$ node Index.  JSServer has started.    

The above output has removed some of the more annoying/favicon.ico request-related sections.

The browser accesses the http://127.0.0.1:8888/and the output is as follows:

node. JS Routing

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.