今天复习了之前利用node写的留言板功能,发现还是不能熟练运用,所以发到论坛上,供以后参考学习。
思路:1,加载静态页面 2,获取表单中的数据 3,提交表单中的数据 4,读取表单中的数据
准备工作:静态页面,css,js;
var http = require("http");
var fs = require("fs");
var path = require("path");
var url = require("url");
var ejs = require("ejs");
var querystring = require("querystring");
var server = http.creatServer(function(req,res){
var realUrl = "http://" + req.headers.host + req.url;
var urlObj = url.parse(realUrl);
switch(url.pathname){
case "/" :
var arr = [];
if(fs.existsSync(filename)){
arr = require("./data.json");
}
ejs.renderFile("index.html",{msg:arr},function(err,html){
if(err) throw err;
res.end(html);
});
break;
case "/publish" :
var str = "";
req.on("data",function(chunk){
str +=chunk;
});
req.on("end",function(){
var msg = querystring.parse(str);
msg.time = new Date().toLocaleString();
var arr = [];
if(fs.existsSync("data.json")){
arr = require("./data.json");
}
arr.unshif(msg)
fs.writeFile("data.json",JSON.stringify(arr),"utf8",function(err){
if(err) throw err;
res.end("<a href='/'>点击进入首页面</a>");
})
})
break;
default:
var filename = path.join(__dirname, urlObj.pathname);
if (fs.existsSync(filename)) {
fs.readFile(filename, function (err, data) {
if (err) throw err;
res.end(data);
})
} else {
res.end();
}
break;
}
});
server.listen(3000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LD Stuido留言板</title>
</head>
<link rel="stylesheet" href="style/base.css">
<link rel="stylesheet" href="style/global.css">
<body>
<div class="wrapper">
<div class="header">
<h1><a href="">wyy留言板</a></h1>
<h2>很靠谱的留言板</h2>
<img src="images/hanoi.jpg" alt="" />
<ul>
<li><a href="">首页</a></li>
<li><a href="">关于</a></li>
</ul>
</div>
<div class="main">
<div class="content">
<% for(var i = 0;i<msg.length;i++)
{
%>
<div class="msg">
<h2> <%=msg[i].title%></h2>
<p>发表于<a href=""><%=msg[i].time%></a> 由 <a href=""><%=msg[i].author %></a></p>
<p><%=msg[i].content%></p>
</div>
<%
}
%>
<div class="msg_form">
<h2>发表留言</h2>
<form action="/publish" method="POST">
<ul>
<li>
<label for="">标题:</label>
</li>
<li>
<input type="text" name="title" class="txt" />
</li>
<li>
<label for="">作者:</label>
</li>
<li>
<input type="text" name="author" class="txt" />
</li>
<li>
<label for="">内容:</label>
</li>
<li>
<textarea name="content" id="" cols="70" rows="5"></textarea>
</li>
<li>
<input type="submit" value="提 交" class="btn" />
</li>
</ul>
</form>
</div>
</div>
<div class="sidebar">
<h2>最新留言</h2>
<ul>
<li><a href="">LAMP架构</a></li>
<li><a href="">JavaScript程序设计</a></li>
<li><a href="">CSS样式</a></li>
<li><a href="">XTHML结构</a></li>
</ul>
</div>
</div>
<div style="clear:both;"></div>
<div class="footer">
<p><a href="">wyy</a> © 2009-2012 版权所有</p>
</div>
</div>
</body>
</html>