nodejs学习笔记08-仿express路由

112 阅读1分钟

前言

把路由抽离出来,便于管理路由。

server.js

const http = require('http');
const router = require("./router");
const listenPort = 8081;

http.createServer(router).listen(listenPort);

router.get("/login", (req, res)=>{
  res.end("login")
})

router.post("/register", (req, res)=>{
  res.end("register")
})
console.log(`Server running at http://127.0.0.1:${listenPort}/`);

router.js

const url = require("url");

function createRouter (){
  const _this = this;
  this._get = {};
  this._post = {};

  function router (req, res){
    const pathName = url.parse(req.url, true).pathname;
    const method = req.method.toLowerCase();
    if(_this[`_${method}`] && _this[`_${method}`][pathName]){
      _this[`_${method}`][pathName](req, res);
    }else {
      res.end('404');
    }
  }

  router.get = (str, callback) => {
    _this._get[str] = callback;
  },
  router.post = (str, callback) => {
    _this._post[str] = callback;
  }
  return router;
}

module.exports = createRouter();