nodejs项目实战教程11——Nodejs封装路由模块

nodejs项目实战教程11——Nodejs封装路由模块

路由封装

复制上一章demo12中的代码到新创建的目录demo13中
在这里插入图片描述
将 app.js 中的路由语句封装到router.js中 app 这个变量下进行统一管理,router.js:

const fs = require('fs')
const http = require('http')
const path = require('path')
const ejs = require('ejs')

// 私有方法
let getFileMine = function(extname){
  // 同步获取数据
  let data = fs.readFileSync('./data/mime.json')
  let mimeObj = JSON.parse(data.toString())
  // 变量名属性只能通过数组的形式进行访问
  // console.log(mimeObj[extname])
  return mimeObj[extname]
}

let app = {
  static:(req,res,staticPath)=>{
    const {url} = req
    const {host} = req.headers
    const myURL = new URL(url,`http://${host}`)
    pathname = myURL.pathname
    // 默认加载页面
    pathname = pathname === '/'?'/index.html':pathname
    // 获取文件后缀
    let extname = path.extname(pathname)
    // 2.通过fs模块读取文件
    if(pathname !== '/favicon.ico'){
      try {
        let data = fs.readFileSync('./' + staticPath + pathname)
        if(data){
          let mime = getFileMine(extname);
          res.writeHead(200, {'Content-Type': ''+ mime +';charset="utf-8"'});
          res.end(data);
          return true
        }
        return false
      } catch (error) {
        return false
      }
    }
  },
  // 处理登录的业务逻辑
  login:(req,res)=>{
    ejs.renderFile('./views/form.ejs',(error,data)=>{
      res.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
      res.end(data);
    })
  },
  news:(req,res)=>{
    res.end('news')
  },
  doLogin:(req,res)=>{
    // 获取post传值
    let postData = ''
    req.on('data',(chunk)=>{
      postData = postData + chunk
    })
    req.on('end',()=>{
      console.log(postData)
      res.end(postData)
    })
  },
  error:(req,res)=>{
    res.end('error')
  }
}

module.exports = app

需要注意的是,需要把ejs模块一同引入到router.js。

调用路由模块

app.js:

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

http.createServer(function (req, res) {
  // 创建静态服务
  let flag = routes.static(req,res,'static')

  const {url} = req
  const {host} = req.headers
  const myURL = new URL(url,`http://${host}`);
  // console.log('myURL',myURL)

  if(!flag){
    console.log('pathname:',pathname)
    if(pathname !== '/favicon.ico'){
      pathname = myURL.pathname.slice(1)
      console.log('其他路由',pathname)
      try {
        routes[pathname](req,res)
      } catch (error) {
        routes['error'](req,res)
      }
    }
  }

}).listen(3000);

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

第一次先调用routes.static方式初始化页面,如果路径不对再尝试其他路由。

下一章 nodejs项目实战教程12——Nodejs封装Express

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sheldon一蓑烟雨任平生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值