Node4 服务器配置

hhh.js

/*
	动态网站开发
*/
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,'index.html'),'utf8',(err,content)=>{
			if(err){
				res.writeHead(500,{
					'Content-Type':'text/plain;charset=utf8'
				})
				res.end('服务器错误,请与管理员联系')
			}
			res.end(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,'result.html'),'utf8',(err,content)=>{
				if(err){
					res.writeHead(500,{
						'Content-Type':'text/plain;charset=utf8'
					})
					res.end('服务器错误,请与管理员联系')
				}
				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('running......')
})

index.html

<!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" name="查询">
	</form>	
</body>
</html>

result.html

<!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": "149",
        "summary": "289"
    },
    "no124":
    {
        "chinese": "120",
        "math": "120",
        "english": "119",
        "summary": "189"
    },
    "no125":
    {
        "chinese": "130",
        "math": "140",
        "english": "109",
        "summary": "239"
    }
}