博客
关于我
Express路由是如何实现的?
阅读量:208 次
发布时间:2019-02-28

本文共 2550 字,大约阅读时间需要 8 分钟。

Express是一个极简的Node.js后端开发框架,它最强大的地方在于它的路由实现,那么它的路由是如何实现的呢?下面给大家分享两段代码,希望大家能够有个简单的认识。

首先是封装的路由模块

var url = require('url');// 封装res.send()方法function changeRes(res) {    res.send = function (data) {        res.writeHead(200, { "Content-Type": "text/html;charset='utf-8'" });        res.end(data);    }};// 定义主服务方法var Server = function () {    var G = this;    // 处理GET和POST请求    this._get = {};    this._post = {};    var app = function (req, res) {        changeRes(res);        // 获取路由        var pathname = url.parse(req.url).pathname;        // 处理URL路由,将结尾加上'/',与注册方法统一        if (!pathname.endsWith('/')) {            pathname = pathname + '/';        };        // 获取请求的方式,GET和POST请求        var method = req.method.toLowerCase();        // 判断方法是否存在        if (G['_' + method][pathname]) {            // 执行POST请求            if (method == 'post') {                var postStr = '';                req.on('data', function (chunk) {                    postStr += chunk;                });                req.on('end', function (err, chunk) {                    req.body = postStr;                    G['_' + method][pathname](req, res);                });                // 执行GET请求            } else {                G['_' + method][pathname](req, res);            };        } else {            res.end('no router');        };    };    // 定义一个GET方法为所有的GET请求注册    app.get = function (string, callback) {        // 将请所有注册路由前后加上'/'        if (!string.endsWith('/')) {            string = string + '/';        };        if (!string.startsWith('/')) {            string = '/' + string;        };        G._get[string] = callback;    };    // 定义一个POST方法为所有的POST请求注册    app.post = function (string, callback) {        // 将请所有注册路由前后加上'/'        if (!string.endsWith('/')) {            string = string + '/';        };        if (!string.startsWith('/')) {            string = '/' + string;        };        G._post[string] = callback;    };    return app;}module.exports = Server();

下面是引入路由并使用。

var http=require('http');var ejs=require('ejs');// 引入封装的路由var app=require('express-route.js');http.createServer(app).listen(3000);// 注册首页的路由(方法)app.get('/',function(req,res){    var msg='这是数据库的数据'    ejs.renderFile('views/index.ejs',{msg:msg},function(err,data){        res.send(data);    })});// 注册login的路由(方法)app.get('/login',function(req,res){    console.log('login');    ejs.renderFile('views/form.ejs',{},function(err,data){        res.send(data);    })});// 注册dologin的路由(方法)app.post('/dologin',function(req,res){    console.log(req.body);      res.send("");})

 

转载地址:http://hgip.baihongyu.com/

你可能感兴趣的文章
MySQL查询报错ERROR:No query specified
查看>>
mysql查询数据库储存数据的占用容量大小
查看>>
MySQL查询数据库所有表名及其注释
查看>>
MySQL查询数据表中数据记录(包括多表查询)
查看>>
MySQL查询结果排序
查看>>
MYSQL查询语句优化
查看>>
mysql查询语句能否让一个字段不显示出来_天天写order by,你知道Mysql底层执行原理吗?
查看>>
MySQL查询语句:揭秘专家秘籍,让你秒变数据库达人!
查看>>
mysql查询超时对PHP执行的影响
查看>>
mysql查询输出到excel文件_如何保存mysql查询输出到excel或.txt文件?
查看>>
mysql查询过程
查看>>
MySQL模拟Oracle序列sequence
查看>>
Mysql模糊查询like效率,以及更高效的写法
查看>>
MySQL死锁套路:一次诡异的批量插入死锁问题分析
查看>>
Mysql死锁问题Deadlock found when trying to get lock;try restarting transaction
查看>>
mysql每个数据库的最大连接数_MySQL数据库最大连接数
查看>>
Mysql流程控制结构,if函数、case结构、if结构、循环结构
查看>>
mysql添加外网访问权限
查看>>
mysql添加用户
查看>>
MySQL添加用户、删除用户与授权
查看>>