使用原生nodejs封装类似express路由

如果看不懂,可以移步我往期的博客地址
express-router.js

//引入相应模块
const http = require('http')
const ejs = require('ejs')
var app = require('./module/router-ww')

//创建web服务器
//每次请求时触发调用app函数,先寻找静态目录,没有就触发调用相应的路由
http.createServer(app).listen(3000)

//修改静态Web目录
app.staticPath('public')

//配置路由
app.get('/',(req,res) =>{
  res.send('首页')
})

app.get('/login',(req,res) =>{
  ejs.renderFile('./views/form.ejs', {},(err, str)=>{
    // str => Rendered HTML string
    res.send(str)
  });
})

app.post('/dologin',(req,res) =>{
  console.log(res.body)
  res.send(res.body)
})

app.get('/news',(req,res) =>{
  res.send('新闻界面')
})

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

router-ww.js

//引入相应模块
const url = require('url')
const path = require('path')
const fs = require('fs')

//扩展方法方法 设置响应数据
let changeRes = (res) =>{
  res.send = (data) => {
    res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"})
    res.write("<head><meta charset='UTF-8'></head>")
    res.end(data)
  }
}

//根据后缀名获取文件类型
let getFileMimeSync = (extname)=> {
  var data = fs.readFileSync('./data/mime.json')
  let mimeObj = JSON.parse(data.toString())
  return mimeObj[extname]
}

//静态Web服务
let createStaticWebServer = (req,res,staticPath) =>{
  //获取请求地址
  let pathname = url.parse(req.url).pathname
  //获取地址后缀名
  let ext = path.extname(pathname)
  // console.log(url.parse(req.url))
    try {
      //为防止路由的检索先执行,故应该使用文件的读取的同步方法
      var data = fs.readFileSync('./'+staticPath+pathname)
      if (data){
        //根据后缀类型设置对应的响应头部
        res.writeHead(200,{"Content-Type":`${getFileMimeSync(ext)};charset='utf-8'`})
        res.end(data)
      }
    }catch (e) {
      // console.log(e)
    }
}

let Server = () => {
  let G = {
    _get:{},  //get路由
    _post:{},  //post路由
    staticPath: 'static', //默认静态Web目录
  }
  let app = function (req,res) {
    //扩展res的方法
    changeRes(res)
    //配置静态Web服务
    createStaticWebServer(req,res,G.staticPath)

    //路由
    let pathname = url.parse(req.url).pathname
    let method = req.method.toLowerCase()
    if(G['_'+method][pathname]){
      if(method == 'get'){
        G._get[pathname](req,res)
      }else{
       // 获取post传值
        let postData = ""
        req.on('data',(chunk)=> {
          postData += chunk
        })
        req.on('end',() => {
          res.body = postData
          G._post[pathname](req,res)
        })
      }
    }else{
      res.send('页面不存在')
    }
  }

  //get
  app.get = function(string,cb){
    //注册方法
    G._get[string] = cb
    //在express-router.js中配置路由的时候执行,就相当于声明一个函数
  }
  //post
  app.post = function (string,cb) {
    G._post[string] = cb
  }
  //静态目录
  app.staticPath = function (staticPath) {
    G.staticPath = staticPath
  }
  return app
}

//向外暴露
module.exports = Server()

./data/mime.json
在这里插入图片描述
./views/form.ejs
在这里插入图片描述
./css/style.css
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值