post.js 插件使用例子
首先,在example目录下,建立post-example目录,建立一个run.js运行文件,还要建立一个public目录用来储存静态资源,public目录下建立一个index.html文件,下面是index.html网页代码。
<!doctype html> <html> <head> <title>write article</title> </head> <body> <form action="http://localhost:3000/post" method="post"> <p><input type="text" name="title"/></p> <p><textarea type="text" name="content" ></textarea></p> <input type="submit" /> </form> </body> </html>
然后编写run.js运行代码:
var fk = require("../..")
,App = fk.App
,app = new App
,static = fk.static
,post = fk.post;
app.use(static(__dirname+"/public"));
app.use(post);
app.post("/post",function(req,res){
res.write("post success!\n");
res.write("----------------\n")
res.write("title: \n")
res.write(req.body.title+"\n");
res.write("content: \n");
res.write(req.body.content);
res.end();
})
app.listen(3000)启动 node run ,然后打开浏览器 localhost:3000/index.html ,这时候会打开表单页。
提交之后,页面会出现:
post success! ---------------- title: my title is post method content: content is about post method and upload.
通过这个例子,看到了post.js中间的作用。通过访问req.body,就可以javascript对象属性的形式访问,岂不美哉!这还不是全部,因为眼下的post.js插件并不支持上传数据的解析,虽然上传也是采用了post方法,但数据结构更为复杂。下一节将探讨上传的数据结构。