在学习nodejs的koa框架和egg框架的路由前你应该知道的。

在使用了koa和egg的路由后发现真的是太太太方便了,通过访问的路径来设置路由,通过路由来定位显示的页面。短短几行代码就把逻辑实现了。通过使用nodejs原生的方式可否实现页面的重定向呢,答案是肯定的,只不过实现的代码会比较多,不过要是简单接触过node的可以看懂。

在新建的文件夹下有一个www目录用来存放html页面,在根目录下新建一个test.js页面。在js文件中引入需要的http模块和path模块以及js模块。

在www目录下分别存在index.html、about.html、list.html三个文件,里面随便写点html代码。

代码显示如下:

/**
 * 路径的分发
 * 1、req对象是Class:http.IncomingMessage的实例对象
 * 2、res对象是Class: http.ServerResponse的实例对象
 */
const http = require('http');
const path = require('path');
const fs = require('fs');
http.createServer((req,res)=>{
  if(req.url.startsWith('/index')){
    fs.readFile(path.join(__dirname,'www','index.html'),'utf8',(err,fileContent)=>{
      if(err){
        res.end('server error');
      }else{
        res.end(fileContent);
      }
    }) 
   }else if(req.url.startsWith('/about')){
    fs.readFile(path.join(__dirname,'www','about.html'),'utf8',(err,fileContent)=>{
      if(err){
        res.end('server error');
      }else{
        res.end(fileContent);
      }
    })
   }else if(req.url.startsWith('/list')){
     fs.readFile(path.join(__dirname,'www','list.html'),'utf8',(err,fileContent)=>{
       if(err){
         res.end('server error');
       }else{
         res.end(fileContent);
       }
     })
   }
}).listen(3000);

通过监听3000端口可以访问各个页面。

通过上面的代码我们发现代码冗余的太多了,我们可以把重复的代码进行抽取,抽取成函数,当需要使用的时候进行调用就可以了

调整后的代码如下所示:

/**
 * 路径的分发
 * 1、req对象是Class:http.IncomingMessage的实例对象
 * 2、res对象是Class: http.ServerResponse的实例对象
 */
const http = require('http');
const path = require('path');
const fs = require('fs');
//抽取函数
//这里传入两个参数,url是传入的html页面的名字,res是传入的response对象。
let readFile = (url,res)=>{
  fs.readFile(path.join(__dirname,'www',url),'utf8',(err,fileContent)=>{
    if(err){
      res.end('server error');
    }else{
      res.end(fileContent);
    }
  })
}
http.createServer((req,res)=>{
  if(req.url.startsWith('/index')){
    readFile('index.html',res);
   }else if(req.url.startsWith('/about')){
    readFile('about.html',res);
   }else if(req.url.startsWith('/list')){
    readFile('list.html',res);
   }else{
     res.writeHead(200,{
       'Content-type':'text/plain;charset=utf8'
     });
     res.end('访问页面不存在...')
   }
}).listen(3000);


是不是简单很多~~~

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值