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");
});
封装第三步(已经开始迷糊了)
网友评论