1.新建一个view目录,在下面创建搜索成绩和查询成绩的页面:
index.tpl:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="http://localhost:3000/score" method="post">
请输入考号:<input type="text" name="code">
<button>确定</button>
</form>
</body>
</html>
score.tpl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>语文:$$chinese$$</li>
<li>数学:$$math$$</li>
<li>英语:$$english$$</li>
<li>综合:$$summary$$</li>
</ul>
</body>
</html>
2.将成绩数据放置在score.json文件里面:
{
"no123":{
"chinese":100,
"math":100,
"english":100,
"summary":100
},
"no124":{
"chinese":100,
"math":100,
"english":100,
"summary":100
},
"no125":{
"chinese":100,
"math":100,
"english":100,
"summary":100
},
"no126":{
"chinese":100,
"math":100,
"english":100,
"summary":100
}
}
3.创建实现查询功能index.js文件:
//引入模块
const path=require("path");
const fs=require("fs");
const http=require("http");
const score=require("./score.json");
const querystring=require("querystring");
//http创建服务,用3000的端口进行监听
http.createServer((req,res)=>{
//判断访问路径
if(req.url.startsWith("/index")){
//读取文件,使用path.join方法拼接路径
fs.readFile(path.join(__dirname,"view","index.tpl"),"utf-8",(err,content)=>{
if(err){
res.writeHead(500,{
"Content-Type":"text/html;charset=utf8"
})
res.end("服务器请求错误")
}
res.end(content)
})
}else if(req.url.startsWith("/score")){//当访问的是score时
let pdata="";
req.on("data",(chunk)=>{
pdata+=chunk;
})
req.on("end",()=>{
let obj=querystring.parse(pdata); //转换为对象
let result=score[obj.code]
//读取文件
fs.readFile(path.join(__dirname,"view","score.tpl"),"utf-8",(err,content)=>{
if(err){
res.writeHead(500,{
"Content-Type":"text/html;charset=utf8"
})
res.end("服务器请求错误")
}
//对返回的数据进行渲染
content=content.replace("$$chinese$$",result.chinese)
content=content.replace("$$math$$",result.chinese)
content=content.replace("$$english$$",result.chinese)
content=content.replace("$$summary$$",result.chinese)
res.end(content)
})
})
}
}).listen(3000,()=>{ //监听
console.log("running====")
})