Nodejs perform specific actions based on the specific request path

Source: Internet
Author: User

1. Processing the request module (requesthandlers.js)

function Start () {

console.log ("Request handler ' start ' was called");

return "Hello start";

}


function upload () {

console.log ("Request handler ' upload ' was called");

return "Hello Upload";

}


Exports.start = start;

Exports.upload = upload;

2. Routing Module (route.js)

Function route (handle,pathname) {

Console.log ("about-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;

3. Server Module (server.js)

var http = require ("http");

var url = require ("url");


function Start (route,handle) {

function ONrequest (request,response) {

var pathname = Url.parse (request.url). Pathname;

if (pathname! = "/favicon.ico") {

Console.log ("Request for" + pathname + "received");

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;

4. Call the appropriate module (index.js)

var server = require ("./server");

var router = require ("./route");

var requesthandlers = require ("./requesthandlers");


var handle = {};

handle["/"] = Requesthandlers.start;

handle["/start"] = Requesthandlers.start;

handle["/upload"] = requesthandlers.upload;


Server.start (Router.route,handle);

5. Executive Index.js

Node Index.js

Visit: Http://localhost:8888/start

Output Result:

Hello start

Visit: Http://localhost:8888/upload

Output Result:

Hello Upload

Visit: Http://localhost:8888/other

Output Result:

404 Not Found


This article is from the "Yan" blog, please be sure to keep this source http://suyanzhu.blog.51cto.com/8050189/1894056

Nodejs perform specific actions based on the specific request path

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.