Dismembered HTTP Server Build

Source: Internet
Author: User
Tags node server

Better read please poke here 1. The simplest HTTP server
// server.jsvar http = require("http");http.createServer(function(request, response) {  response.writeHead(200, {"Content-Type": "text/plain"});  response.write("Hello World");  response.end();}).listen(8888);//  node server.js// 打开http://localhost:8888/,你会看到一个写着“Hello World”的网页~

It's so simple, this article is finished ~

Oh,no
Too young, too

2. Dismemberment Code
    • var http = require("http")
      • Request (require) node. js's own HTTP module and assign it to an HTTP variable
    • createServer
      • Listen Method-Numeric parameter specifies the port number that the HTTP server listens on
    • createServerThe parameters
      • Event-driven callbacks
        • Whenever our server receives a request, the function is called
    • Request Processing

      When the ONrequest () function is triggered, there are two parameter objects
      • Request
      • Response

        // 发送一个HTTP状态200和HTTP头的内容类型response.writeHead(200, {"Content-Type": "text/plain"});// 添加HTTP主体内容response.write("Hello World");// 完成响应response.end();
3. Module encapsulation

This step we turn server.js into a real node. JS Module

    1. function encapsulation
      Wrap our script inside a function and export the encapsulation function

      var http = require("http");function start() {  function onRequest(request, response) {    console.log("Request received.");    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hello World");    response.end();  }  http.createServer(onRequest).listen(8888);  console.log("Server has started.");}exports.start = start;
    2. Module reference

      // 如主文件名为index.js,写入var server = require("./server");server.start();

      Performnode index.js

4. Routing

All request data is in the requests object, data parsing, URL required, QueryString module

Come on, let's try to find the browser request path ~

4.1 Getting the route
var http = require("http");var url = require('url')function start(){  function onRequest(req, res){    var url = url.parse(req.url)    // 打印 url 信息    console.log('server start url', url)    res.writeHead(200, {"content-type": "text/plain"})    res.end()  }  http.createServer(onRequest).listen(8888)}exports.start = start

Request.url parameter printing:

4.2 There is a way to find

Introducing routing Processing

    • Create Route.js, process routing information, introduce the module on the index page, and execute as a parameter to the start function in the server.
    • Parse each request and get its URL path for processing
// server.jsvar http = require("http");var url = require('url')function start(route){  function onRequest(req, res){    var pathname = url.parse(req.url).pathname    route(pathname)    res.writeHead(200, {"content-type": "text/plain"})    res.end()  }  http.createServer(onRequest).listen(8888)}exports.start = start
// route.jsfunction route(pathname){  console.log('route', pathname)}exports.route = route// index.js  引入routevar server = require('./server')var router = require('./route')server.start(router.route)

The above code we have achieved a way to find

To avoid multiple if. else: We pass a series of requests through objects

  • First create a Requestmanager module, export multiple processing functions
  • Creating a Managers object: mapping different routes to the processing method
  • Pass the mapping of a route to a function as a parameter to the server
  • The processing result of calling route in
  • Server

     //requestmanager.jsfunction start () {Console.log (' Route-----start ') return ' hello start '}function next () {Console.log (' route-----Next ') return ' Hello Next '}exports.star t = Startexports.next = next  
     //Index.jsvar server = require ('./readfile ') var router = Require ('./route ') var requestmanager = require ('./requestmanager ') var managers = []managers['/'] = requestmanager.startmanagers['/start ' = requestmanager.startmanagers['/next '] = RequestManager.nextserver.start ( Router.route, managers)//Http://localhost:8888/start, the browser will output "Hello start"//Http://localhost:8888/next will output "Hello Next "//Http://localhost:8888/chaoran will output" 404 ". 
  • Manager: Each route provides a corresponding handler function

    // server.jsvar http = require("http");var url = require('url')function start(route, manager){  function onRequest(req, res){    var pathname = url.parse(req.url).pathname    console.log('server request for', pathname)    var content = route(pathname, manager)    res.writeHead(200, {"content-type": "text/plain"})    res.write(content)    res.end()  }  http.createServer(onRequest).listen(8888)}exports.start = start
  • Remove the routed event from the managers for processing

    // route.jsfunction route(pathname, managers){  console.log('rrr', pathname)  if(typeof managers[pathname] == 'function'){    return managers[pathname]()  }else {    console.log('managers no found')    return ''  }}exports.route = route

Well, it can be used, it is occasionally hung (") ~→

As for the parallel in node and how to implement non-blocking, next time we combine examples to learn ~

Reference:

    • Node Getting Started

    • In layman Nodejs

Dismembered HTTP Server Build

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.