簡(jiǎn)易源碼
let http=require('http');
let url=require('url');
function createAppAplication(){
let appRoutes=[];//路由
const methods=http.METHODS; //所有網(wǎng)絡(luò)請(qǐng)求方法
let app=(req,res)=>{
let index=0;
function next(error){
if(index===appRoutes.length)
{
res.end(`can not ${methodName} ${pathname}`);
return;
}
let methodName=req.method.toLowerCase();
let {pathname}=url.parse(req.url,true);
let {method,path,handler}=appRoutes[index++];
//如果中間件右報(bào)錯(cuò)信息
if(error)
{
console.log('處理報(bào)錯(cuò)');
console.log(handler);
if(handler.length===4)
{
handler(error,res,req,next)
}
else{
next(error);
}
return;
}
//如果是中間件
if(method==='middle')
{
//
if(path==='/' || path===pathname || pathname.startsWith(path))
{
handler(req,res,next);
}
else{
next();
}
}
else{
if((method===methodName|| method==='all') && (path===pathname || path==='*'))
{
handler(req,res);
return;
}
else{
//沒(méi)有匹配到接著匹配
next();
}
}
}
next();
// //獲取當(dāng)前請(qǐng)求方法
// let methodName=req.method.toLowerCase();
// //獲取請(qǐng)求路徑 依賴(lài) url 模塊
// let {pathname}=url.parse(req.url,true);
// for(let {method,path,handler} of appRoutes)
// {
// if(method===methodName && path===pathname)
// {
// handler(req,res);
// return;
// }
// }
// //都沒(méi)有匹配到
// res.end(`can not ${methodName} ${pathname}`);
}
/**
* 收集中間件
*/
app.use=function(path,handler){
if(typeof path ==='function')
{
handler=path;
path='/';
}
appRoutes.push({
method:'middle',
path,
handler,
})
}
//內(nèi)置中間件 獲得請(qǐng)求信息
app.use(function(req,res,next){
let {pathname,query}=url.parse(req.url,true);
let hostname=req.headers['host'].split(':')[0];
req.pathname=pathname;
req.query=query;
req.hostname=hostname;
next();
})
//配置 app.get 等
methods.forEach((method)=>{
//獲得都是大寫(xiě)的 轉(zhuǎn)為小寫(xiě)
method=method.toLowerCase();
app[method]=(path,handler)=>{
let item={
method,
path,
handler
}
//console.log(item);
appRoutes.push(item);
}
})
//所有請(qǐng)求都配匹配到
app.all=function(path,handler){
appRoutes.push({
method:'all',
path,
handler,
})
}
//端口監(jiān)聽(tīng)
app.listen=function(){
let server=http.createServer(app);
server.listen(...arguments);
}
return app;
}
module.exports=createAppAplication;
測(cè)試
const express=require('./express');
let app=express();
app.use(function(req,res,next){
//設(shè)置請(qǐng)求頭
res.setHeader('Content-Type','text/html;charset=utf-8');
next();
})
app.use('/name',function(req,res,next){
//設(shè)置請(qǐng)求頭
console.log('進(jìn)入name的 中間件');
// next("報(bào)錯(cuò)中間件");
next();
})
app.get('/name',(req,res)=>{
let {pathname,hostname,query}=req;
let message={
pathname,
hostname,
query
}
res.end(`請(qǐng)求信息:${JSON.stringify(message)}: 返回結(jié)果:于學(xué)文`);
})
app.get('/age',(req,res)=>{
res.end('27');
})
app.use((error,req,res,next)=>{
next(error);
})
app.use((error,req,res,next)=>{
console.log(error);
})
app.listen(3000,()=>{
console.log('監(jiān)聽(tīng)30010端口');
})
image.png