美文网首页
仿照express封装模块

仿照express封装模块

作者: Wrestle_Mania | 来源:发表于2019-11-19 16:05 被阅读0次
const app = function() {
  console.log("app");
};

app.get = function() {
  console.log("app.get");
};

app.post = function() {
  console.log("app.post");
};

app();
app.get();

上面两个方法都能运行

var G = {};

const app = function(req, res) {
  if (G["login"]) {
    G["login"](req, res);
  }
};

// 定义一个get方法
app.get = function(string, callback) {
  G[string] = callback;
};

// 执行get方法
app.get("login", function(req, res) {
  console.log("login" + req);
});

setTimeout(() => {
  app("req", "res");
}, 2000);

封装的第一步

var G = {};

const app = function(req, res) {
  if (G["login"]) {
    G["login"](req, res);
  }
};

app.get = function(string, callback) {
  G[string] = callback;
};

const http = require("http");

http.createServer(app).listen(8080);

app.get("login", (req, res) => {
  res.end("fuck");
});

封装的第二步

  • 创建一个服务,一旦有访问,就会触发app方法的执行
const http = require("http");
const url = require("url");

var G = {};

const app = function(req, res) {
  res.writeHead(200, { "Content-Type": "text/html;charset=utf8" });
  let pathname = url.parse(req.url, true).pathname;
  if (!pathname.endsWith("/")) {
    pathname = pathname + "/";
  }
  if (G[pathname]) {
    G[pathname](req, res);
  } else {
    res.end("路由不存在");
  }
};

app.get = function(string, callback) {
  if (!string.endsWith("/")) {
    string += "/";
  }
  if (!string.startsWith("/")) {
    string = "/" + string;
  }
  G[string] = callback;
};

http.createServer(app).listen(8080);

app.get("login", (req, res) => {
  res.end("login");
});

app.get("register", (req, res) => {
  res.end("register");
});

封装第三步(已经开始迷糊了)

相关文章

网友评论

      本文标题:仿照express封装模块

      本文链接:https://www.haomeiwen.com/subject/bpxgictx.html