从零开始学Node.js(九):Node.js封装静态web服务、路由

从零开始学Node.js(九):Node.js封装静态web服务、路由


​ ​ ​ ​ ​ ​ ​ ​

​ ​ ​ ​ ​ ​ ​ ​ 第九节涉及到的项目文件目录如下所示。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uM73A67J-1587200541938)(C:\Users\NayelyA\AppData\Roaming\Typora\typora-user-images\image-20200418154931694.png)]

封装静态web服务

​ ​ ​ ​ ​ ​ ​ ​ 本节所要封装的静态web服务呢,是基于从零开始学Node.js(八)中的小项目。主要过程分为这样几个过程:

  • 封装web服务器的主要代码:在module文件夹下创建route.js文件,将原项目app.js中创建web服务器的代码封装到route.js中的static函数中。

  • 此时需要注意的是,可能会涉及修改路径。

​ ​ ​ ​ ​ ​ ​ ​ route.js代码如下所示。

const fs=require('fs');
const path=require('path');
const url=require('url');

//私有方法
let getFileMime  = function(extname){
    var data=fs.readFileSync('./data/mime.json');
    let mimeObj=JSON.parse(data.toString());
    return mimeObj[extname];
}

exports.static=function(request,response,staticPath){
    //获取地址
  let pathname=url.parse(request.url).pathname;
  pathname=pathname=='/'?'/index.html':pathname;
  //获取后缀名
  let extname=path.extname(pathname);
  //通过fs模块读取文件
  if(pathname!='/favicom.ico'){
    fs.readFile('./'+staticPath+pathname,(err,data)=>{
      if(err){
        response.writeHead(404,{'Content-Type': 'text/html;charset="utf-8"'});
        response.end("该页面不存在");
      }
      let mime=path.extname(extname);
      response.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});
      response.end(data);
    })
  }
}

​ ​ ​ ​ ​ ​ ​ ​ app.js代码如下所示。通过require引入我们自定义的route模块,然后调用static方法创建静态web服务。

const http = require('http');
const routes=require('./module/route');


http.createServer(function (request, response) {

  //创建静态web服务
  routes.static(request,response,'static');
  
}).listen(8081);

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

路由

​​ ​ ​ ​ ​ ​ ​ ​ 路由指的是针对不同请求的URL,处理不同的业务逻辑。

路由时一个URI和一个特定的HTTP方法(get/post等)组成的,涉及到应用如何响应客户端对某个网站节点的访问。

​ ​ ​ ​ ​ ​ ​ ​ 比如说,http://域名//login,处理登录的业务逻辑,那么这个就是路由。路由的实现需要引入url模块。

​ ​ ​ ​ ​ ​ ​ ​ 新建routetest.js,通过url获取请求路径pathname,然后通过if语句进行判断,执行相应的业务逻辑。提示:对于访问站点下的静态资源,其实我们都将相关方法封装到了route模块中。

const http = require('http');
const routes = require('./module/route');
const url=require('url');

http.createServer(function (request, response) {

    //创建静态web服务
    routes.static(request, response, 'static');

    //路由
    let pathname = url.parse(request.url).pathname;

    if (pathname == '/login') {
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("执行登录");
    } else if (pathname == '/register') {
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("执行注册");
    }else{
        response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("页面不存在~");
    }

}).listen(8081);

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


​ ​ ​ ​ ​ ​ ​ ​ 启动之后,发现127.0.0.1:8081/index.html显示页面不存在,我们写的这个127.0.0.1:8081/login等等可以正常运行,这是为啥呢?我们知道访问index.html的功能实际上该静态服务器本身是可以处理的(封装到route中了),显示页面不存在可以说明创建静态服务器还没有完成,直接跑到了下面这个判断pathname的过程中了。这又是为啥呢?因为route.js中读取文件的方法是个异步方法,所以我们需要把程序改成同步的。

​ ​ ​ ​ ​ ​ ​ ​ 修改route.js内容。注意我们将readFile改成了readFileSync

const fs = require('fs');
const path = require('path');
const url = require('url');

//私有方法
let getFileMime = function (extname) {
  var data = fs.readFileSync('./data/mime.json');
  let mimeObj = JSON.parse(data.toString());
  return mimeObj[extname];
}

exports.static = function (request, response, staticPath) {
  //获取地址
  let pathname = url.parse(request.url).pathname;
  console.log(pathname);
  pathname = pathname == '/' ? '/index.html' : pathname;
  console.log(pathname);
  //获取后缀名
  let extname = path.extname(pathname);
  //通过fs模块读取文件
  if (pathname != '/favicom.ico') {
    try {
      let data = fs.readFileSync('./' + staticPath + pathname);
      if (data) {
        let mime = getFileMime(extname);
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end(data);
      }
    } catch (error) {

    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值