node基础12:动态网页

1.显示动态网页

又到了激动人心的时刻,马上就可以使用node创建动态网站了,其原理为:

  • 在HTML模板中使用占位符
  • 根据请求路径,确定需要返回的页面
  • 根据请求参数来确定静态模板中占位符的值
  • 使用正则匹配将占位符匹配为真实值
  • 再res.write()到浏览器的

代码如下:

// server.js
var http = require("http");
var url = require('url');
var router = require('./router');

http.createServer(function(req, res){
    if ( req.url !== '/favicon.ico'){
        pathname = url.parse(req.url).pathname.replace(/\//,'');
        console.log(pathname);
        try {
            router[pathname](req, res);
        } catch(e) {
            console.log('error:'+e);
            res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
            res.write(e.toString());
            res.end();
        };
    }
}).listen(3000);
console.log("server running at http:127.0.0.1:3000");
/**
 * router.js
 */
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');

module.exports = {
    login: function(req, res){
        var post ='';
        req.on('data', function(chunk){
            post += chunk;
        });
        req.on('end', function(){
            post = querystring.parse(post);
            array = ['username', 'password'];
            fs.readFile('./login.html', function(err, data){
                if( err){
                    console.log(err);
                    res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'})
                    res.write(err.toString());
                    res.end();
                } else {
                    res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'})
                    data = data.toString();
                    for(var i = 0; i < array.length; i++){
                        var reg = new RegExp("{{"+array[i]+"}}", 'g');
                        console.log(reg);
                        post[array[i]] = post[array[i]] == undefined ? '':post[array[i]];
                        data = data.replace(reg, post[array[i]]);
                        console.log(post[array[i]]);
                    }
                    res.write(data);
                    res.end();
                }
            })
        })
    },
    register:function(req, res){
        fs.readFile('.register.html', function(err, data){
            if(err) {
                console.log(err);
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'})
                res.write(err.toString());
                res.end();
                return;
            } else{
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
                res.write(data);
                res.end();
            }
        })
    },
    showImage:function(req, res){
        fs.readFile('./test.png',function(err, data){
            if (err) {
                console.log(err);
                return;
            } else{
                console.log("开始读取图片");
                res.writeHead(200, {'Content-Type':'image/jpeg'});
                res.write(data);
                res.end();//写在互调函数外面会报错的哟
            }
        })
    }

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <img src="./showImage" alt="">
    <h1>收到参数:username:{{username}}</h1>
    <h1>收到参数:password:{{password}}</h1>
    <form action="./login" method="POST">
        <p>
            <span>name</span>
            <input type="text" name="username">
        </p>
        <p>
            <span>password</span>
            <input type="text" name="password">
        </p>
        <p>
            <input type="submit" value="登录">
        </p>
    </form>
</body>
</html>

 

posted on 2017-01-05 23:07  码先生  阅读(888)  评论(0编辑  收藏  举报