web开发概述(09):初步实现动态调用

示例:简易版成绩查询

myserver.js

/*
    动态网站开发示例

    mini版成绩查询功能
 */

const http = require('http');
const path = require('path');
const fs = require('fs');
const querystring = require('querystring');
const scoreData = require('./scores.json');

http.createServer((req,res) =>{
    //查询成绩入口  /query
    if(req.url.startsWith('/query') && req.method === 'GET'){
        fs.readFile(path.join(__dirname,'view','index.tpl'),'utf-8',(err,content)=>{
            if(err){
                res.writeHead(500,{
                    'Content-type':'text/plan;charset=utf8'
                });
                res.end('服务器错误,请与管理员联系!' + err);
            }

            res.end(content);

        });
    }else if(req.url.startsWith('/score') && req.method === 'POST'){
        //路由(请求路径+请求方式)(分发)
        //获取成绩的结果 /score
        let pdata = '';
        req.on('data',(chunk) => {
            pdata += chunk;
        });

        req.on('end',()=>{
            let obj = querystring.parse(pdata);
            let result = scoreData[obj.code];
            fs.readFile(path.join(__dirname,'view','result.tpl'),'utf8',(err,content)=>{
                if(err){
                    res.writeHead(500,{
                        'Content-Type':'text/plain;charset=utf8'
                    });
                    res.end('服务器错误,请与管理员联系' + err);
                }

                //返回内容之前需要进行数据渲染
                content = content.replace('$$chinese$$',result.chinese);
                content = content.replace('$$math$$',result.math);
                content = content.replace('$$english$$',result.english);
                content = content.replace('$$summary$$',result.summary);
                res.end(content);
            });
        });

    }

}).listen(3000,()=>{
    console.log("服务启动…… ฅʕ•̫͡•ʔฅ");
})

模板

/view/index.tpl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查询成绩</title>
</head>
<body>
    <form action="http://localhost:3000/score" method="post">
        请输入卡号:<input type="text" name="code">
        <input type="submit" value="查询">
    </form>
</body>
</html>

/view/result.tpl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成绩结果</title>
</head>
<body>
    <div>
        <ul>
            <li>语文:$$chinese$$</li>
            <li>数学:$$math$$</li>
            <li>外语:$$english$$</li>
            <li>综合:$$summary$$</li>
        </ul>
    </div>
</body>
</html>

测试数据
scores.json

{
  "no123": {
    "chinese": "100",
    "math": "140",
    "english": "140",
    "summary": "220"
  },
  "no124": {
    "chinese": "140",
    "math": "143",
    "english": "142",
    "summary": "250"
  },
  "no125": {
    "chinese": "110",
    "math": "113",
    "english": "112",
    "summary": "210"
  }
}
posted @ 2020-10-14 11:49  mrtransition  阅读(93)  评论(0)    收藏  举报