目标
使用express实现一个监听3000端口的http服务如下
const express = require ( 'express' ) ;
const app = express ( ) ; app. get ( '/' , ( req, res) => { res. end ( 'Hello Express' ) ;
} )
app. get ( '/users' , ( req, res) => { res. end ( JSON . stringify ( { name: 'abc' } ) )
} )
app. listen ( 3000 , ( ) => { console. log ( '[server] server is running at http://localhost:3000 ' ) ;
} )
const express = require ( './lxpress.js' ) ;
即需要完成以下几个操作 1.会有一个router数组,当使用app.get方法时,会将路径和回调函数传入 2.调用listen方法时,会创建一个http服务.该服务会从router数组中取出所有的路由进行监听.然后根据传入的参数进行监听
实现
const http = require ( 'http' ) ;
let routers = [ ] ;
class Application { get ( ) { } , listen ( ) { }
}
module. exports = ( ) => { return new Application ( ) ;
}
get逻辑的实现. 1.会接收2个参数,path和handler 2.将参数推进routers中 3.为了方便以后和POST方法区分,新增一个method属性
get ( path, handler) { routers. push ( { path, method: 'GET' , handler} )
}
listen逻辑的实现 1.在里面会创建一个http服务,该服务接收request和response两个参数 2.对routers里面的每一项进行解析,并为每一项指定路由处理函数handler 3.接收的参数用…arguments展开执行
listen ( ) { const server = http. createServer ( ( req, res) => { const { pathname} = url. parse ( req. url, true ) ; for ( let router of routers) { const { path, method, handler} = router; if ( path === pathname && req. method === method) { return handler ( req, res) ; } } } ) server. listen ( ... arguments) ;
}
总体代码如下:
const http = require ( 'http' ) ;
const url = require ( 'url' ) ; const router = [ ] ;
class Application { get ( path, handler) { router. push ( { path, method: 'get' , handler} ) } listen ( ) { const server = http. createServer ( ( req, res) => { const { pathname } = url. parse ( req. url, true ) ; for ( const item of router) { const { path, method, handler } = item; if ( pathname === path && req. method. toLowerCase ( ) === method) { return handler ( req, res) ; } } } ) server. listen ( ... arguments) ; }
} module. exports = ( ) => { return new Application ( )
}