我们仅仅实现express框架的路由和中间件功能。
我们先来看一下效果咋样。
const express = require("../express");
const app = express();
app.get("/getName", function (req, res, next) {
res.end("hello world");
next();
})
app.use("/", function (req, res, next) {
console.log("这是第一个中间件")
next("worry");
})
app.use("/getName", function (err,req, res, next) {
console.log(err + "这是错误处理中间件")
})
app.listen(8000, () => {
console.log("8000服务器已经启动");
});
访问http://localhost:8000/getName(hello world已经打印)
终端显示。
我们在看看带有参数的路径
app.get("/getName/:name/:age", function (req, res, next) {
res.end("over")
console.log(req.params);
});
app.listen(8000, () => {
console.log("8000服务器已经启动");
});
大致上先实现了这些功能,我们来看一下怎么做的。先看一下整体的结构
app.listen 这个函数用于开启一个服务器,代码很简单。(app是回调函数)
app.listen = function (...args) { //就是开启一个服务器
let server = http.createServer(app);
server.listen.apply(server, args);
};
接下来就是在app上面挂载一些类似get,post的路由(也是中间件)。为了方便,我们遍历http.MEHODS上面的方法,然后给每个方法绑定一个回调。这里还需要对路径进行一些处理,比如上面出现的/getName/:name/:age等这样的,需要利用正则处理一些,为了方便后面的匹配工作,而且需要把参数都保留下来。
http.METHODS.forEach((method) => { //遍历http上面的一些方法
method = method.toLocaleLowerCase(); //转小写
app[method] = func