node. JS Routing

Source: Internet
Author: User

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

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.