UNPKG

tainanle-express

Version:

execl download

52 lines (48 loc) 1.31 kB
// 导入模块 const http = require("http"); // 定义app对象 const app = { // 1 收集开发者自定义路由 routes: [ // {method, path, callback} ], get(path, callback) { // this就是app对象 this.routes.push({ method: "GET", path, callback, }); }, post(path, callback) { // this就是app对象 this.routes.push({ method: "POST", path, callback, }); }, }; app.listen = function () { http .createServer((req, res) => { // res.setHeader("content-type", "text/html;charset=utf-8"); // res.end("可以监控用户所有请求,后期根据路由匹配"); // 2 每次访问 req.url 请求地址 req.method 请求方式 // 去收集的路由中匹配 let route = app.routes.find((item) => { // 当return真的时候就会把当前的item赋值给route并终止遍历 return item.method == req.method && item.path == req.url; }); // 匹配到了,直接走callback // 匹配不到,返回404 if (route) { route.callback(req, res); } else { res.end(`${req.method} ${req.url} 404 NOT FOUND`); } }) .listen(...arguments); }; // 导出模块 module.exports = app;