博客
关于我
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 1406
查看>>
mysql - 视图
查看>>
MySQL - 解读MySQL事务与锁机制
查看>>
MTTR、MTBF、MTTF的大白话理解
查看>>
mt_rand
查看>>
mysql -存储过程
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>