Node.js creates and encapsulates a static WEB server

Preparations:
prepare a material portal similar to the one in the picture
: materials and complete code required for this article
Insert picture description here

1. Detailed steps

Create http service

// app.js
const http = require('http');  // 加载http服务模块

http.createServer((req, res) => {
    
    
  res.writeHead(200, {
    
    'Content-Type': 'text/html;charset=utf-8'});
  res.end();   // 结束响应
}).listen(3000);  // 设置端口号

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

Get URL

// 我们要获取类似这样的url,来展示对应的内容
http://localhost:3000/index.html
let pathName = req.url;
console.log(pathName);  // /index.html   /favicon.ico

We found that two requests were sent, and the request /favicon.ico needs to be filtered out. At the same time, we need to deal with empty addresses, the code is as follows:

// app.js
const http = require('http');  // 加载http服务模块

http.createServer(function (req, res) {
    
    
  let pathName = req.url;
  pathName = pathName == '/' ? '/index.html' : pathName;

  if(pathName != '/favicon.ico'){
    
    
     res.writeHead(200, {
    
    'Content-Type': 'text/html;charset=utf-8'});
     res.end();
  }
}).listen(3000);

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

Read file

First load the fs module, if the requested page is not found, load the 404 page

// app.js
const http = require('http');  // 加载http服务模块
const fs = require('fs');

http.createServer(function (req, res) {
    
    
  // http://127.0.0.1:3000/login.html

  // 1. 获取地址
  let pathName = req.url;
  pathName = pathName == '/' ? '/index.html' : pathName;

  // 2. 通过fs模块读取文件
  if(pathName != '/favicon.ico'){
    
    
    fs.readFile(`./static${
      
      pathName}`,(err,data) => {
    
    
      if(err){
    
    
        fs.readFile('./static/404.html',(err,data404)=>{
    
    
          if(err){
    
    
            console.log('404')
          }else{
    
    
            res.writeHead(404, {
    
    'Content-Type': 'text/html;charset=utf-8'});
            res.end(data404);
          }
        })
      }else{
    
    
        res.writeHead(200, {
    
    'Content-Type': 'text/html;charset=utf-8'});
        res.end(data);
      }
    })
  }
}).listen(3000);

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

At this point, we can already see the effect as follows:
Insert picture description here
set the request header

Because we set all requested file headers to'Content-Type':'text/html;charset=utf-8';
this is obviously a wrong approach. For example: css file should be set to'text/css', js file should be set to'text/javascript'.

We first create a folder, name it module, and create a js file common.js
code in the folder as follows:

// common.js
const fs = require('fs');

exports.getFileMime = (extName) => {
    
    
  // readFileSync 为 readFile 的同步方法
  let data = fs.readFileSync('./data/mime.json'); // 注意:因为该方法在 app.js 引用,所以相对位置应以app.js为基点
  let mimeObj = JSON.parse(data.toString());
  return mimeObj[extName]
}

We need to set the corresponding file format according to the file suffix of the corresponding request, so we need to introduce the path module. Then use the path.extname() method to get the corresponding suffix name.

// app.js
const http = require('http');  // 加载http服务模块
const fs = require('fs');
const path = require('path');
const common = require('./moudle/common');

http.createServer(function (req, res) {
    
    
  // http://127.0.0.1:3000/login.html

  // 1. 获取地址
  let pathName = req.url;
  pathName = pathName == '/' ? '/index.html' : pathName;
  
  // 获取后缀名 path.extname();
  let extname = path.extname(pathName)
  console.log(pathName)

  // 2. 通过fs模块读取文件
  if(pathName != '/favicon.ico'){
    
    
    fs.readFile(`./static${
      
      pathName}`,(err,data) => {
    
    
      if(err){
    
    
        fs.readFile('./static/404.html',(err,data404)=>{
    
    
          if(err){
    
    
            console.log('404')
          }else{
    
    
            res.writeHead(404, {
    
    'Content-Type': 'text/html;charset="utf-8"'});
            res.end(data404);
          }
        })
      }else{
    
    
        let mime = common.getFileMime(extname) // 根据对应的后缀名,获取对应的文件格式
        res.writeHead(200, {
    
    'Content-Type': `${
      
      mime};charset="utf-8"`});
        res.end(data);
      }
    })
  }
}).listen(3000);

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

The result is as shown in the figure:
Insert picture description here
However, the corresponding picture is not loaded. This is because: these two files are not loaded, because the request address has parameters and cannot be recognized, so it is necessary to introduce the url module and use the url.parse() method to parse the address into an address without parameters;
Insert picture description here
complete code :

// app.js
const http = require('http');  // 加载http服务模块
const fs = require('fs');
const path = require('path');
const url = require('url');

const common = require('./moudle/common');

http.createServer(function (req, res) {
    
    
  // http://127.0.0.1:3000/login.html

  // 1. 获取地址
  let pathName = url.parse(req.url).pathname;
  pathName = pathName == '/' ? '/index.html' : pathName;
  
  // 获取后缀名 path.extname();
  let extname = path.extname(pathName)
  
  // 2. 通过fs模块读取文件
  if(pathName != '/favicon.ico'){
    
    
    fs.readFile(`./static${
      
      pathName}`,(err,data) => {
    
    
      if(err){
    
    
        fs.readFile('./static/404.html',(err,data404)=>{
    
    
          if(err){
    
    
            console.log('404')
          }else{
    
    
            res.writeHead(404, {
    
    'Content-Type': 'text/html;charset="utf-8"'});
            res.end(data404);
          }
        })
      }else{
    
    
        let mime = common.getFileMime(extname) // 根据对应的后缀名,获取对应的文件格式
        res.writeHead(200, {
    
    'Content-Type': `${
      
      mime};charset="utf-8"`});
        res.end(data);
      }
    })
  }
}).listen(3000);

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

The results are shown in the figure:
Insert picture description here

2. Encapsulate the static WEB server

Insert picture description here
As shown in the figure above, create a new staticApp.js under the NODEJS directory and create a new route.js under the moudle directory to encapsulate the static web server.

//  route.js
const fs = require('fs');
const path = require('path');
const url = require('url');

// 私有方法
function getFileMime(extName){
    
    
  // readFileSync 为 readFile 的同步方法
  let data = fs.readFileSync('./data/mime.json'); // 注意:因为该方法在 app.js 引用,所以相对位置应以app.js为基点
  let mimeObj = JSON.parse(data.toString());
  return mimeObj[extName]
}


exports.static = (req,res,staticPath) => {
    
    

  // 1. 获取地址
  let pathName = url.parse(req.url).pathname;
  pathName = pathName == '/' ? '/index.html' : pathName;
  
  // 获取后缀名 path.extname();
  let extname = path.extname(pathName)
  
  // 2. 通过fs模块读取文件
  if(pathName != '/favicon.ico'){
    
    
    fs.readFile(`./${
      
      staticPath}${
      
      pathName}`,(err,data) => {
    
    
      if(err){
    
    
        fs.readFile('./static/404.html',(err,data404)=>{
    
    
          if(err){
    
    
            console.log('404')
          }else{
    
    
            res.writeHead(404, {
    
    'Content-Type': 'text/html;charset="utf-8"'});
            res.end(data404);
          }
        })
      }else{
    
    
        let mime = getFileMime(extname) // 根据对应的后缀名,获取对应的文件格式
        res.writeHead(200, {
    
    'Content-Type': `${
      
      mime};charset="utf-8"`});
        res.end(data);
      }
    })
  }
}
// staticApp.js
const http = require('http');  // 加载http服务模块
const routes = require('./moudle/routes')

http.createServer(function (req, res) {
    
    
  routes.static(req,res,'static')
}).listen(8000);

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

The results are shown in the figure:
Insert picture description here

Guess you like

Origin blog.csdn.net/ZYS10000/article/details/114108580