Node.js完整的响应html页面(包括css,js文件)

主要思想就是任何一个静态文件也应该做响应,一个获取静态文件都应当请求来处理,这是主要思想。

同时要注意两点。第一,对于不同的文件类型,比如html,css,js,请求头里面的文件类型需要根据不同的文件类型注明,

第二,文件的路径需要表达准确,fs.readFile方法的第一个参数path是已起服务的文件为根目录,这里就是以server.js文件的所在目录为根目录

 

文件目录

文件夹public

      Index.html

      Css文件夹

           Reset.css

           Index.css

      Js文件夹

          vue.min.js

          Index.js

Server.js

 

Server.js和文件夹publi同级

 

来看server.js代码

var http = require('http');

var fs = require('fs');

var url = require('url');

 

 // 创建服务器

http.createServer( function (request, response) { 

   // 解析请求,包括文件名

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

   var postfix = pathname.match(/(.[^.]+|)$/)[0];//取得后缀名

   // 输出请求的文件名

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

 

   // 从文件系统中读取请求的文件内容

   fs.readFile(pathname.substr(1), function (err, data) {

      if (err) {

         console.log(err);

        // HTTP 状态码: 404 : NOT FOUND

         // Content Type: text/plain

         response.writeHead(404, {'Content-Type': 'text/html; charset=utf-8'});

      }else{            

         // HTTP 状态码: 200 : OK

         // Content Type: text/plain

         console.log(postfix);

         if(postfix==='html'){

             response.writeHead(200, {'Content-Type': 'text/html'});   

         }else if(postfix==='css'){

            response.writeHead(200, {'Content-Type': 'text/css'});

         }

         else if(postfix==='js'){

            response.writeHead(200, {'Content-Type': 'application/javascript'});

         }else{

         }

         // 响应文件内容

         response.write(data.toString());       

      }

      //  发送响应数据

      response.end();

   });

}).listen(8080);

 

// 控制台会输出以下信息

console.log('Server running at http://127.0.0.1:8080/');

 

最后在命令行输入node server.js 把服务器起起来

然后在浏览器打开http://127.0.0.1:8080/public/index.html

原文地址:https://www.cnblogs.com/ranyonsue/p/10348799.html