表单Demo,验证用。
- 目录结构
mkdir demo
cd demo
npm init -y
npm install --save express body-parser
type nul>server.js
mkdir src
cd src
type nul>index.html
cd ..
mkdir data
cd data
type nul>user.json
- users.json
{
"tom": {
"id": 1,
"password": "abc@tom",
"job": "teacher"
},
"jack": {
"id": 2,
"password": "def#jack",
"job": "police"
},
"lucy": {
"id": 3,
"password": "ijk&lucy"
}
}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>form</title>
<style>
#root{
width:500px;
height:300px;
overflow:hidden;
}
#part1,#part2{
width:300px;
height:300px;
}
label{
float:left;
margin:5px;
}
input[type=submit]{
margin-left:45px;
}
</style>
</head>
<body>
<div id="root">
<div id="part1">
<h3>当前用户</h3>
<ul id="userlist"></ul>
<a href="#part2">注册?</a>
</div>
<div id="part2">
<form method='post' action='/addUser'>
<label>名字: <input type="text" name='name'></label>
<label>密码: <input type='password' name='pass' /></label>
<input type="submit" value='注册'>
</form>
</div>
</div>
<script>
function getDataFromServer(callback){
var XHR = new XMLHttpRequest();
XHR.open('get','/userlist');
// XHR.onreadystatechange = function(){
// if(XHR.readyState===4 && XHR.status===200){
// var data = JSON.parse(XHR.response);
// console.log(data);
// }
// }
XHR.onload = function(){
var data = JSON.parse(XHR.response);
callback(Object.keys(data));
}
XHR.send();
}
function populateList(data){
var fragment = document.createDocumentFragment();
data.forEach(item => {
var li = document.createElement('li');
var text = document.createTextNode(item);
li.appendChild(text);
fragment.appendChild(li);
});
var ul = document.querySelector('#userlist');
ul.appendChild(fragment);
}
window.onload = function(){
getDataFromServer(populateList);
}
</script>
</body>
</html>
- server.js
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
app.use(express.static(path.join(__dirname,'src')));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended:true
}));
const jsonPath = path.join(__dirname,'data/users.json');
app.get("/userlist",function(req,res){
fs.readFile(jsonPath,'utf-8',(err,data)=>{
res.end(data);
})
})
app.post('/addUser',function(req,res){
const {name,pass} = req.body;
fs.readFile(jsonPath,'utf-8',(err,data) => {
data = JSON.parse(data);
data[name] = {
"pass":pass
}
fs.writeFile(jsonPath,JSON.stringify(data,null,4),'utf-8',err => {
res.writeHead(200,'OK',{'Content-Type':"text/html;charset=UTF-8"});
res.end('<h1>注册成功!</h1>');
});
})
});
app.listen(3030,function(){
console.log("listening on *:3030");
})
- 效果图
node server.js
,localhost:3030