虽然是做后端的,但前端的一些东西多多少少还是要会一点的。这个是跟着视频敲得,学习嘛,都是从模仿开始。
一、目录结构
二、数据准备(json格式的成绩数据)
{
"no123":{
"chinese":"103",
"math":"103",
"english":"103",
"summary":"103"
},
"no124":{
"chinese":"104",
"math":"104",
"english":"104",
"summary":"104"
},
"no125":{
"chinese":"105",
"math":"105",
"english":"105",
"summary":"105"
}
}
二、页面准备
Ⅰ、index 成绩查询页面
<!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>
Ⅱ、成绩展示页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>成绩</title>
</head>
<body>
<ul>
<li>语文:$$chinese$$</li>
<li>数学:$$math$$</li>
<li>外语:$$english$$</li>
<li>综合:$$summary$$</li>
</ul>
</body>
</html>
三、JS 准备
/**
*动态网站的开发
* 成绩查询
*/
const http = require("http");
const path = require("path");
const fs = require("fs");
const querystring = require("querystring"); //这些是各个模块,不要忘记
const scoreData = require("../data/score.json");
http.createServer((req,res)=>{
//路由 (请求路径 + 请求方式)
//查询成绩的入口地址 /query
//注意这个 页面路径不要弄错了
if(req.url.startsWith("/query") && req.method == "GET"){
fs.readFile(path.join(__dirname,"../view","index.html"),"utf8",(err,conent)=>{
if(err){
res.writeHead(500,{
"Content-Type":"text/plain;charset=uf8"
});
res.end("服务器错误,请与管理员联系");
}
res.end(conent); //注意这个 content 不要拼错了,我之前拼错了排查了好久,怎么看都没错
});
}else if(req.url.startsWith("/score")){ // &&req.method == "POST" 这里严谨的话加上 请求类型
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.html"),"utf8",(err,content)=>{
if(err){
res.writeHead(500,{
"Content-Type":"text/plain;charset=uf8"
});
res.end("服务器错误,请与管理员联系");
}
//返回内容之前要进行数据渲染
console.log("中文:"+result.chinese);
console.log("数学:"+result.math);
//将页面上的字符串$$chinese$$ 替换为json 中获取到的数据
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); //注意这一个不要忘记了
});
});
}
//获取成绩的结果 /score
}).listen(3000,()=>{
console.log("running...");
})
四、运行以及效果展示
Ⅰ、运行 nodeJS
Ⅱ、访问成绩查询页面,并输入
Ⅲ、点击查询,页面跳转,成绩显示