Node小练习:自定义路由

注册页面login.html, 通过用户名和密码验证成功后,跳向内容页index.htmlindex.html页面动态显示内容:admin 管理员

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <style>
        div.content {
            width: 500px;
            margin: 0 auto;
        }
    </style>
</head>
<body>

    <div class="content">
        <img src="../static/images/3.png" alt="">
        <h1>登录页面</h1>
        <form action="/loginCheck">
        <table>
            <tr>
                <td>username:</td>
                <td><input name="username"/></td>
            </tr>
             <tr>
                <td>password:</td>
                <td><input name="password"/></td>
            </tr>
             <tr>
                <td></td>
                <td><input type="submit" value="login">&nbsp;<input type="reset" value="reset"></td>
            </tr>
        </table>
        </form>
    </div>


</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>内容页面</title>
    <style>
        div.content {
            width: 500px;
            margin: 0 auto;
        }
    </style>
</head>
<body>

    <div class="content">
        <img src="../static/images/3.png" alt="">
        欢迎你,${username}, 角色:${ role }
    </div>
</body>
</html>

server.js

var http = require('http')
var url = require('url');

var Router = require('./router') //自定义路由模块


http.createServer(function(req, res) {
    if ("/favicon.ico" !== req.url) {
        try {
            Router.setErrorPage('./app/404.html');

            Router.map({
                '/login': {
                    'tpl':'./app/login.html'
                },
                '/loginCheck': {
                    'tpl':'./app/index.html',
                    'action': function(query) {
                        if (query['username'] === 'admin' && query['password'] === 'admin') {
                             this.data = query;
                             this.data.role = '管理员';
                             return true;
                        }
                        return '/login';
                     }
                }
            }, req, res);
        } catch(err) {
            res.writeHeader(200, {'content-Type': 'image/jpeg','charset': 'utf-8' });
            res.write('500 error');
        }

    }
    res.end('')
}).listen(3000)

console.log('server listen at ' + 3000);

router.js

var url = require('url')
const fs = require('fs');
var path = require('path');

var ROOT_PATH = path.resolve(__dirname);

module.exports = {
    setErrorPage(errorPage) { //设置错误页面
        this.errorPage = errorPage;
    },
    map: function(mapping, req, res) {
        var pathname = url.parse(req.url).pathname;
        if (/\.png$/.test(pathname)) { //处理图片
            res.writeHeader(200, {'content-Type': 'image/jpeg','charset': 'utf-8' });
            var img = ROOT_PATH + pathname;
            //If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
            var data = fs.readFileSync(img); 
            res.write(data);
        } else { //处理页面
            res.writeHeader(200, {'content-Type': 'text/html','charset': 'utf-8' });

            var obj = mapping[pathname];

            var tpl = this.errorPage;

            var query = url.parse(req.url, true).query;

            var flag = (!obj.action) || obj.action(query); //回调函数

            if (obj && flag) {
                tpl = (flag === true ? obj.tpl : mapping[flag].tpl);
            }

            var html = fs.readFileSync(tpl, "utf-8");
            if (obj.data) { //动态网页
                for (var p in obj.data) {

                    var regExp = new RegExp("\\$\\{\\s*"+p+"\\s*\\}","gi");
                    html = html.replace(regExp,obj.data[p]);
                }    
            }
            res.write(html);
        }

    }
}

http://xhope.top/wp-content/uploads/2016/11/1.jpg
http://xhope.top/wp-content/uploads/2016/11/2.jpg