node. js First Knowledge 07

Source: Internet
Author: User

Previously said, Nodejs is not a Web container, Apache is a Web container, if you want node to achieve Apache effect, that is, http://127.0.0.1:3000/a/b/c.html appear such a link to access the page, so need to program to achieve this effect

The file directory is as follows, only need to see Static.js and static this folder is good

Static.js

var http = require ("http"), var url = require ("url"), var fs = require ("FS"), var path = require ("path"); Http.createserver (Fu     Nction (req,res) {var pathname= url.parse (Req.url). Pathname;     if (pathname== "/") {pathname= "index.html";     }//Extended name var extname = path.extname (pathname); Fs.readfile ("./static/" +pathname,function (err,data) {if (err) {///If this file does not exist can return a 404 page fs.r Eadfile ("./static/404.html", function (err,data) {res.writehead (404,{"Content-type": "Text/html;charset=utf8"                 });             Res.end (data);         }) return;         };         MIME type, is//web file: text/html//jpg file: image/jpg var mime = getmine (extname);         Res.writehead (200,{"Content-type": MIME});     Res.end (data); });            }). Listen (3000, "127.0.0.1");//If you have a different format extension name, you can continue with the case, function Getmine (extname) {switch (extname) {box ". html":            return "text/html";        Break Case". jpg": Return "image/jpg";        Break            Case ". png": Return "Image/png";        Break            Case ". css": return "TEXT/CSS";    Break }}

The purpose of Getmine is because in some old browsers, if there is no MIME file type, Content-type, the browser will not recognize and load him

Thus, in node, the basic Web container is written

node. js First Knowledge 07

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.