How to create a node-based HTTP server

Source: Internet
Author: User
Tags readfile

First, create an HTTP server.

varHTTP = require (' http ');functionserve (request,response) {console.log (Request.method); //method of RequestConsole.log (Request.url);//the URL in the request, which contains only the path name, is not the full URLConsole.log (Request.header)//GET request HeaderResponse.statuscode= 200; //set the response type, encoded as utf-8.     //when the server returns a resource to the browser, it should also tell the browser what type of file it is and how to parse it. If not specified, it may cause garbled characters.Response.setheader (' Content-type ', ' text/html;charset=utf-8 '); Response.setheader (' Name ', ' zfpx '); Response.Write (NewDate (). toString ()); Response.End ();}varServer =Http.createserver (serve); Server.listen (3000);

If we want to read the contents of other files, we need to first import the FS module, which is the module that reads the files .

 var fs = require (' FS ');  
Function serve (request,response) { Request.url; // // When the server returns a resource to the browser, you should also tell the browser what type of file it is. How to parse response.setheader (' Content-type ', ' text/html;charset=utf-8 ' // If we want to return the contents of another file, we need to read the other files first. The FS module is required to read the file fs.readfile (' index.html ', function (Err,data) {Response.Write (data); Response.End (); })}

But there is another problem: When parsing the returned HTML code, when the parsing process encounters resources on the referenced server (additional CSS,JS code, pictures, and so on), it needs to send the request to the server again, but no matter what the request is sent, The server returned all the index.html files. At this point, we need to make a decision on different request resources to return different types of resources.

functionserve (request,response) {varURL =Request.url; if(url = = '/')) {        //set the response type, encoded as utf-8.         //when the server returns a resource to the browser, it should also tell the browser what type of file it is and how to parse itResponse.setheader (' Content-type ', ' text/html;charset=utf-8 '); //if we want to return the contents of another file, we need to read the other files first, then we need the FS module to read the fileFs.readfile (' index.html ',function(Err,data) {Response.Write (data);        Response.End (); })    }Else if(url = = '/style.css ')) {Response.setheader (' Content-type ', ' text/css;charset=utf-8 '); //if we want to return the contents of another file, we need to read the other files first, then we need the FS module to read the fileFs.readfile (' Style.css ',function(Err,data) {Response.Write (data);        Response.End (); })    }

One page, we may request a very high number of static resources, if each time adding an else if the page is obviously more complex, and is not conducive to maintenance. So we want to encapsulate all the static resource requests in one function.

functionParsemime (pathname) {varReg =/\. (html| js| css| json| Txt| ico| JPG)/i; if(reg.test (pathname)) {//gets the suffix name of the request file        varsuffix = reg.exec (pathname) [1].touppercase (); //gets the MIME type of the current file according to the suffix name of the requested file        varSuffixmime = "Text/plain"; Switch(suffix) { Case"HTML": Suffixmime= "Text/html";  Break;  Case"CSS": Suffixmime= "Text/css";  Break;  Case"JS": Suffixmime= "Text/javascript";  Break;  Case"JSON": Suffixmime= "Application/json";  Break;  Case"ICO": Suffixmime= "Application/octet-stream";  Break;  Case"JPG": Suffixmime= "Image/jpg";  Break; }    }    returnSuffixmime;}

In fact, node also provides a third-party module that can automatically help us determine the MIME type of the file, we also need to use a third-party module "Mine".

varMIME = require (' MIME '));functionserve (request,response) {varURL =Request.url; if(url = = '/')) {        //set the response type, encoded as utf-8.         //when the server returns a resource to the browser, it should also tell the browser what type of file it is and how to parse itResponse.setheader (' Content-type ', ' text/html;charset=utf-8 '); //if we want to return the contents of another file, we need to read the other files first, then we need the FS module to read the fileFs.readfile (' index.html ',function(Err,data) {Response.Write (data);        Response.End (); })    }Else{static (Url,response)}}functionstatic (Url,response) {Response.setheader (' Content-type ', mime.lookup (URL) + '; Charset=utf-8 '); //if we want to return the contents of another file, we need to read the other files first, then we need the FS module to read the fileFs.readfile (Url.slice (1),function(Err,data) {Response.Write (data);    Response.End (); })    }

Now our URLs are similar to http://localhost:3000/index.html, that is, the client simply gets the data, does not involve sending data to the server side.

As we said earlier, Request.url gets the content after ' 3000: ', so when we need to send some content to the server, say Http://localhost:3000/index.html/?name= "Xiaoyu". At this time Request.url get is/index.html/?name= "Xiaoyu".

Such a URL obviously can no longer be used as a basis for us to determine the path, so we have to further deal with this URL. In fact, node provides a more powerful URL parsing library to us, the library is the "URL." This library is able to parse the entire full URL path.

Delivery address: URL Module Learning Summary

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.