nodejs7: 原生nodejs模块化封装路由 + ejs


在这里插入图片描述
思路:将所有路由都封装在 routes 内,在app.js中把每次可能的路径信息都只是调用routes,routes中统一格式做适配。
在app.js中:
1.创建静态web服务(这个是用作访问静态站点或者文件比如路径后加入index.html等等)
2.实现路由(这个是类似于www.xxx.con/login 这种形式,没有访问文件但是需要实现某种操作)
以上两种情况都被看做 routes中的方法,其中1的名字肯定叫static,2每一个可能的路由都弄一个名字,名字的参数是一样的,所以可以直接用变量替代访问。

// app.js
const http = require('http');
const routes = require('./module/routes');
const url = require('url');

http.createServer(function (req, res) {
    console.log(req.method);
    // 创建静态web服务
    routes.static(req, res, 'my_website');
    // 路由
    let pathname = url.parse(req.url).pathname.replace("/", "");
    try {
        routes[pathname](req, res);
    } catch (error) {
        routes['error'](req, res);
    }

}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');
//routes.js
const fs = require('fs');
const path = require('path');
const url = require('url');
const ejs = require('ejs');

let getFileMime = function (extname) {
    let data = fs.readFileSync('./data/mime.json');
    let mimeObj = JSON.parse(data.toString());
    return mimeObj[extname];
}

let app = {
    login: (req, res) => {
        ejs.renderFile('./views/form.ejs', (err, data) => {
            res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
            res.end(data);
        })
    }, 
    register: (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/html' + ';charset="utf-8"' });
        res.end('注册页面');
    },
    dologin: (req, res) => {
        var postData = '';
        req.on('data', (chunk) => postData += chunk); // chunk是片段
        req.on('end', () => {
            console.log(postData);
            res.end(postData);
        });
    },
    static: (req, res, staticPath) => {
        // 1. 获取地址
        let pathname = url.parse(req.url).pathname;
        pathname = pathname=='/'?'/index.html':pathname;
        let extname = path.extname(pathname);
        // 2. 通过fs模块读取文件
        if (pathname != '/favicon.ico') {
            // 同步方法
            try {
                let data = fs.readFileSync('./' + staticPath + pathname);
                if (data) {
                    let mime = getFileMime(extname);
                    // console.log('  -' + extname + ' ' + mime);
                    res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
                    res.end(data);
                }
            } catch (err) {

            }
        }
    }, 
    news: (req, res) => {
        let msg = '这是一个数据';
        let list = [
            {
                title: "新闻1",
            },
            {
                title: "新闻2",
            },
            {
                title: "新闻3",
            }
        ];
        ejs.renderFile('./views/news.ejs', {
            msg: msg, 
            newslist: list
        }, (err, data) => {
            res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
            res.end(data);
        })
    },
    error: (req, res) => {
        res.end('error');
    }
}

module.exports = app;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值