var http = require('http');
var fs = require('fs');
// 处理接收到的数据 a=12&b=23 -> {a:12,b:23}
// 方法使用:qs.parse()解析成对象
var qs = require('querystring');
var websites = []; // 保存请求的数据
var app = http.createServer(function (req, res) {
var postData = '';
if (req.method === 'GET') {
switch (req.url) {
case '/index.html':
// 读取指定的html文件
fs.readFile('index.html', function (err, data) {
res.writeHeader(200, { 'Content-Type': 'text/html' })
res.end(data.toString())
})
break;
case '/find.html':
fs.readFile('find.html', function (err, data) {
res.writeHeader(200, { 'Content-Type': 'text/html' })
res.end(data.toString())
})
break;
case '/add.html':
fs.readFile('add.html', function (err, data) {
res.writeHeader(200, { 'Content-Type': 'text/html' })
res.end(data.toString())
})
break;
}
} else if (req.method === 'POST') {
switch (req.url) {
case '/add.js':
//数据的累积
req.on('data', function (chunck) {
postData += chunck; //每次执行数据放入
})
//数据接收完毕
req.on('end', function () {
console.log(postData);
var website = qs.parse(postData);
console.log(website.domain)
console.log(website.name)
console.log(website.age)
console.log(website.click);
websites.push(website)
var html = `
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>数据</title>
</head>
<body>
<table>
`
for(var i=0; i<websites.length ; i++){
var row = '<tr>'+'<td>'+websites[i].domain+'</td>'+
'<td>'+websites[i].name+'</td>'+
'<td>'+websites[i].age+'</td>'+
'<td>'+websites[i].click+'</td>'
+'</tr>';
html+=row;
}
html +=`
</table>
</body>
</html>`
res.writeHeader(200, {
'content-type': 'text/html',
'charset-set': 'utf-8'
})
res.end(html)
})
break;
}
}
})
app.listen(1000)
上述代码中请求的路径页面及js:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>南瓜的乐园</title>
</head>
<body>
<h2>欢迎来到板栗南瓜的乐园</h2>
<a href="/add.html">add</a>
<a href="/delete.html">delete</a>
<a href="/edit.html">edit</a>
<a href="/find.html">find</a>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>南瓜的乐园</title>
</head>
<body>
<h1>add</h1>
<form action="add.js" method="POST">
domain name: <input type="text" name="domain" /> <br>
name: <input type="text" name="name"><br>
age : <input type="text" name="age"/> <br>
click : <input type="text" name="click"/> <br>
<input type="submit" value="add">
</form>
</body>
</html>