只匹配路由
向外暴露一个createApp函数,函数返回一个app对象。声明routes(路由表)存放路由。app.get(),app.post(),app.all()等方法会往routes中添加路由项,createApp函数内部创建一个http服务,app.listen()监听端口。当客户端请求是遍历routes路由表,如果有匹配的路由,则执行该路由项的handler函数。
const http = require('http');
const url = require('url');
function createApp(){
let app = {};
//路由表,app.get(),app.post()等方法相当于往路由表中添加路由规则,然后等客户端来请求匹配
let routes = [];
//将所有http请求方式都添加到app对象中
http.METHODS.forEach(method => {
method = method.toLowerCase();
app[method] = (path, handler) => {
let router = {
method,
path,
handler
};
//将当前写好的路由规则储存,等待客户端来请求匹配
routes.push(router);
}
})
//app.all全部匹配,一般用于404
app.all = (path, handler) => {
let router = {
method: 'all', //如果method为all,则全部匹配
path,
handler
};
//将当前写好的路由规则储存,等待客户端来请求匹配
routes.push(router);
}
//请求服务器
let server = http.createServer((req, res) => {
let method = req.method.toLowerCase(); //当前请求方式
let {pathname} = url.parse(req.url); //当前请求地址
console.log(method, pathname, routes);
//遍历储存好的routes路由规则
for(let i = 0; i < routes.length; i++){
//如果有匹配的路由就执行它的handler函数
let m = routes[i].method;
let p = routes[i].path;
//如果method为all,path为*,则所有地址都可匹配
if((m == method || m == 'all') && (p == pathname || p == '*')){
console.log('路由匹配到了')
routes[i].handler(req, res);
}
}
});
//监听端口函数
app.listen = function(){
server.listen(...arguments);
}
return app;
}
module.exports = createApp;
中间件
同样定义app.use方法往routes路由表中添加路由项,不同的是该路由项的method属性值为"middle",用来区分中间件与普通路由。当客户端请求,创建next函数迭代遍历routes路由表,如果当前请求与method: "middle"的路由项匹配,那么按照中间件来执行,否则按照普通路由执行。
const http = require('http');
const url = require('url');
function createApp(){
let app = {};
//路由表,app.get(),app.post()等方法相当于往路由表中添加路由规则,然后等客户端来请求匹配
let routes = [];
//将所有http请求方式都添加到app对象中
http.METHODS.forEach(method => {
method = method.toLowerCase();
app[method] = (path, handler) => {
let router = {
method,
path,
handler
};
//将当前写好的路由规则储存,等待客户端来请求匹配
routes.push(router);
}
})
//app.all全部匹配,一般用于404
app.all = (path, handler) => {
let router = {
method: 'all', //如果method为all,则全部匹配
path,
handler
};
//将当前写好的路由规则储存,等待客户端来请求匹配
routes.push(router);
}
//app.use使用中间件
app.use = (path, handler) => {
if(handler === undefined){
handler = path;
path = '/';
}
let router = {
method: 'middle',
path,
handler
}
routes.push(router);
}
//请求服务器
let server = http.createServer((req, res) => {
let method = req.method.toLowerCase(); //当前请求方式
let {pathname} = url.parse(req.url); //当前请求地址
console.log(method, pathname, routes);
let i = 0;
//使用next()迭代遍历routes路由表
function next(){
if(i >= routes.length) return; //迭代结束
let m = routes[i].method;
let p = routes[i].path;
let handler = routes[i].handler;
i++;
//如果是中间件
if(m == 'middle'){
if(p == '/' || p == pathname || pathname.startsWith(p+'/')){
handler(req, res, next);
}else{
next();
}
}else{
// console.log(method, m, pathname, p);
//如果有匹配的路由就执行它的handler函数
//如果method为all,path为*,则所有地址都可匹配
if((m == method || m == 'all') && (p == pathname || p == '*')){
console.log('路由匹配到了')
handler(req, res);
}else{
next();
}
}
}
next();
});
//监听端口函数
app.listen = function(){
server.listen(...arguments);
}
return app;
}
module.exports = createApp;
自己动手写个static中间件
const url = require('url');
const path = require('path');
const fs = require('fs');
function static(basePath){
return (req, res, next) => {
let {pathname} = url.parse(req.url);
let p = path.resolve(path.join(basePath, pathname));
// console.log(p);
fs.stat(p, (err, stats) => {
if(err) return next();
//如果当前目录存在且为文件,则读取文件响应给客户端
if(stats.isFile()){
let reader = fs.createReadStream(p);
return reader.pipe(res);
}else{ //否则匹配下一条路由
next();
}
})
}
}
module.exports = static;
打印访问日志中间件
const fs = require('fs');
module.exports = function(req, res, next){
//客户端ip地址
let clientIP = req.connection.remoteAddress;
//访问时间
let time = new Date().toGMTString();
//请求方式
let method = req.method;
//请求地址
let url = req.url;
let str = `${clientIP} [${time}] ${method} ${url}\n`;
fs.appendFile('logs/access.log', str, err => {
if(err){
console.log('访问日志打印错误', err);
}
next();
})
}
执行文件app.js
const express = require('./my-express');
const static = require('./my-static');
const fs = require('fs');
const app = express();
app.use(static('./public'));
// app.use((req, res, next) => {
// console.log('恭喜你成功使用中间件');
// next();
// })
app.get('/', (req, res) => {
res.end('hello world');
})
app.post('/post', (req, res) => {
res.end('恭喜你post请求成功');
})
app.all('*', (req, res) => {
res.end('404');
})
app.listen(8888, () => {
console.log('server listening at port 8888');
})
网友评论