nodejs11-路由的封装(下)

如果说我比别人看得更远些,那是因为我站在了巨人的肩上. ——牛顿 伊萨克.牛顿 (lsaac Newton )

  • 先看一下express官网的路由
// invoked for any requests passed to this router
router.use(function(req, res, next) {
  // .. some logic here .. like any other middleware
  next();
});

// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
  // ..
});

清晰脱俗,简洁易懂

取其精华,去其糟粕

新建demo1.js


var http = require('http')
var url = require('url')
var Obj = {}
var app = function (req, res) {


  var pathname = url.parse(req.url).pathname
  res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'})
  
  if (!pathname.endsWith('/')){
    pathname = `${pathname}/`
  }

  if (Obj[pathname]) {
    Obj[pathname](req,res)
  } else {
    res.end('无效路径')
  }
}


app.get = function (string, callback) {
  if (!string.endsWith('/')) {
    string = `${string}/`
  }
  if (!string.startsWith('/')) {
    string = `/${string}`
  }
  // 注册方法
  Obj[string] = callback
}


app.get('login', function(req, res) {
  res.end('login')
})

app.get('register', function(req, res) {
  res.end('register')
})


http.createServer(app).listen('8083')

console.log('Server is Running in 8083')


照葫芦画瓢,先学个七分

补充
一个线程只能隶属于一个进程,但是一个进程是可以拥有多个线程的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容