Express 源码学习

const http = require('http')
const url = require('url') 
const fs = require('fs')
let router = []
class Express {
    get(path,cb){
        router.push({
            method:'GET',
            path,
            cb
        })
    }
    post(){
        router.push({
            method:'POST',
            path,
            cb
        })
    }
    listen(){
        const serve = http.createServer(function(req,res){
            router.forEach(item=>{
                if(req.url===item.path && req.method === item.method){
                    item.cb(req,res)
                }
            })
            if(req.url==='/'&&req.method==='GET'){
                fs.readFile('./index.html',function(err,data){
                    res.end(data)
                })
            }
        }).listen(...arguments) 
    }
}


module.exports = function(){
    return new Express()
}

const express = require('./1.js')
const app =  express()
app.get('/a',function(req,res){
    res.end(JSON.stringify({name:'dasdasd'}))
})
app.listen(3000)

没有实现中间件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。