(精华)2020年7月6日 Node.js express(手写版)

//myexpress.js
const http = require('http');
const url = require('url');
let routers = [];
class Application {
     
    get(path, hander) {
     
        routers.push({
     
            path,
            method: 'get',
            hander
        });
    }
    listen2() {
     
        const server = http.createServer(function (req, res) {
     
            const {
     
                pathname
            } = url.parse(req.url, true);

            var tet = routers.find(v => {
     
                return v.path == pathname && req.method.toLowerCase() == v.method
            })

            tet && tet.hander(req, res);

        })
        //在Application原型上添加listen方法匹配路径, 执行对应的hander
        server.listen(...arguments)
        //  server.listen(aa,fn)
    }
}
module.exports = function () {
     
    return new Application();
}
const express = require('./myexpress.js');

const app = express();
app.get('/',(req,res) => {
     
    res.end('Hello world')
})
app.get('/users',(req,res) => {
     
    res.end(JSON.stringify({
     name:'abcooooo'}))
})
app.get('/list',(req,res) => {
     
    res.end(JSON.stringify({
     name:'list'}))
})
app.listen2(3200 , () => {
     
    console.log('Example listen at 3200')
})

你可能感兴趣的:(Node.js,javascript,前端)