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方式初始化页面,如果路径不对再尝试其他路由。

猜你喜欢

转载自blog.csdn.net/qq_39055970/article/details/121854994