Node学习-静态web服务

  通过node服务实现静态网页访问,切换路由(url)地址时,更换页面(读取不同的本地文件并展示在网页上) -> 静态web服务

  第一步:搭建node服务器

      引入http模块 : 

1     var http = require('http');
2     http.createServer(function (request, response) {
3     response.writeHead(200, {'Content-Type': 'text/plain'});
4     response.end('Hello World');
5     }).listen(8081);
6 
7     console.log('Server running at http://127.0.0.1:8081/');

      小窍门:使用快捷方式 :键入node-http-server;

  

  第二步:读取本地文件渲染至页面:

      ①:获取路由地址,明确需访问文件名称

        - 引入url模块解析网页路由信息获取当前路由:

  

1     const url = require('url');
2     // 1、获取路由地址
3     let pathName = url.parse(req.url).pathname;

      ②:读取文件,处理本地文件(页面文件)不存在问题:

        

 1   if (pathName != '/favicon.ico') {
 2     // 2、通过fs模块 读取文件
 3     fs.readFile('/static' + pathName, async (err, data) => {
 4       if (err) {
 5         // 404
 6         res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
 7         res.end('页面不存在');
 8       }
 9     })
10   }

      ③:将文件内容渲染至网页页面:

1       res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
2 
3       res.end(data);

  此时会出现样式(.css),数据(.json)等文件在页面的效果并未出现效果,因为Content-Type(示字符集的设定)非指定类型造成;

  需使用node-mime(本人2020-12-23日发布内容)文档:

    - 引入fs模块并读取node-mime文件

    

1     exports.getFileMime = function (estnames) {
2         var data = fs.readFileSync('./data/mime.json');
3         mimeObj = JSON.parse(data)
4         return mimeObj[estnames];
5     }

  在node服务页面引入并在文件渲染之前处理内容:(总)

  

 1   const http = require('http');
 2   const fs = require('fs');
 3   const common = require('./module/common'); // 引入上一步方法
 4   const path = require('path');
 5   const url = require('url');
 6 
 7   common.getFileMime('.json')
 8 
 9   http.createServer(function (req, res) {
10     // 1、获取地址
11     let pathName = url.parse(req.url).pathname;
12     pathName = pathName == '/' ? '/index.html' : pathName;
13     // path.extname()  // 可以获取后缀名
14     let extName = path.extname(pathName)
15     if (pathName != '/favicon.ico') {
16       // 2、通过fs模块 读取文件
17       fs.readFile('/static' + pathName, async (err, data) => {
18         if (err) {
19           // 404
20           res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
21           res.end('页面不存在');
22         }
23         
24         let mime = await common.getFileMime(extName)
25 
26         res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
27 
28         res.end(data);
29 
30       })
31     }
32 
33   }).listen(3001);

    可正常显示页面以及.css/.js等文件效果。

原文地址:https://www.cnblogs.com/chenghuayike/p/14201547.html