Node.js 从入门到放弃(六)

仿express框架封装路由

创建router.js文件

import url from 'url'

// 事件中心
const eventEmitter = {}

export const app = (req, res) => {
    let pathname = url.parse(req.url).pathname
    // 由于pathname前面总是带/,这里处理路径统一形式/pathname/
    if (!pathname.endsWith('/')) {
        pathname = pathname + '/'
    }
    // 事件中心调用
    if (eventEmitter[pathname]) {
        eventEmitter[pathname](req, res)
    } else {
        res.end('no routers')
    }
}

// 注册路由,类似发布订阅
app.get = (pathName, callback) => {
	// 处理路径变成/pathName/
    if (!pathName.endsWith('/')) {
        pathName = pathName + '/'
    }
    if (!pathName.startsWith('/')){
        pathName = '/' + pathName 
    }
    // 注入事件中心
    eventEmitter[pathName] = callback
}

server.js 使用封装的路由

import http from 'http'
import { app } from './router.js'
http.createServer(app).listen(3000)
console.log('Server is run at port 3000')

app.get('login', (req, res) => {
    res.end('login')
})
app.get('register', (req, res) => {
    res.end('register')
})

加入getpost处理

router.js

import url from 'url'
// 添加send方法
const setHeader = res => {
    res.send = data => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf8'})
        res.end(data)
    }
}
// 事件中心
const eventEmitter = {
    get: {},
    post: {}
}

export const app = (req, res) => {
    setHeader(res)

    let {pathname, query} = url.parse(req.url)
    // 获取method,方便判断post或get
    const method = req.method.toLowerCase()

    if (!pathname.endsWith('/')) {
        pathname = pathname + '/'
    }

    if (method === 'get' && eventEmitter.get[pathname]) {
        req.query = query
        eventEmitter.get[pathname](req, res)
    } else if (method === 'post' && eventEmitter.post[pathname]) {
        let postStr = ''
        req.on('data', chunk => {
            postStr+=chunk
        })
        req.on('end', (err, chunk) => {
            req.body = postStr
            eventEmitter.post[pathname](req, res)
        })
       
    } else {
        res.end('no routes')
    }
}

app.get = (pathName, callback) => {
    if (!pathName.endsWith('/')) {
        pathName = pathName + '/'
    }
    if (!pathName.startsWith('/')){
        pathName = '/' + pathName 
    }
    eventEmitter.get[pathName] = callback
}

app.post = (pathName, callback) => {
    if (!pathName.endsWith('/')) {
        pathName = pathName + '/'
    }
    if (!pathName.startsWith('/')){
        pathName = '/' + pathName 
    }
    eventEmitter.post[pathName] = callback
}

server.js

import http from 'http'
import ejs from 'ejs'
import { app } from './router.js'

http.createServer(app).listen(3000)
console.log('Server is run at port 3000')

// 根据路由渲染login.ejs模板
app.get('login', (req, res) => {
    ejs.renderFile('./views/login.ejs', {}, (err, data) => {
        res.send(data)
    })
})
// login.ejs 模板中form表单的请求方式为post
app.post('handleLogin', (req, res) => {
    res.send(req.body)
})
// login.ejs 模板中form表单的请求方式为get
app.get('handleLogin', (req, res) => {
    res.send(req.query)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值