nodejs学习之表单提交(1)
nodejs作为一门后端语言,接触的最多的是它的框架,但是它本身的api我觉得更是非学不可,所有才有了这篇文章
表单提交是最基本的也是最实用的入门实例
HTML:
<!DOCTYPE html> <html> <head> <title>main</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div id="div1" style="width: 350px;"> <form id="form1" method="post" action="postlogin" > <fieldset> <legend>表单1</legend> 姓名:<input type="text" name="username" /><br /> 学历:<select name="education"> <option value="中学">中学</option> <option value="大专">大专</option> <option value="本科">本科</option> <option value="硕士">硕士</option> <option value="博士">博士</option> </select><br /> 住址:<input type="text" name="address" /> 隐藏:<input name="hide" disabled="disabled" value="111" /> <input type="submit" value="提交" /> </fieldset> </form> </div> </body> </html>
server端:
var httpserver = require("http"); var qs = require("querystring"); var url = require("url"); var fs = require("fs"); httpserver.createServer(onRequest).listen(3000); function onRequest(request,response) { var pathname = url.parse(request.url).pathname; if(pathname=="/") //访问表单页面 { response.writeHead(200,{"Content-Type":"text/html"}); fs.readFile("index.html","utf-8",function(e,data){ response.write(data); response.end(); }); } else if(pathname=="/postlogin") //处理post方式请求 { var urlstr=""; request.addListener("data",function(postdata){ urlstr+=postdata; //接收到的表单数据字符串,这里可以用两种方法将UTF-8编码转换为中文 var jsondata = qs.parse(urlstr); //转换成json对象 var decodedata = decodeURIComponent(urlstr); //对表单数据进行解码 console.log(urlstr); console.log(jsondata); console.log(decodedata); urlstr = decodedata; }); request.addListener("end",function(){ response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}); response.write(urlstr); response.end(); }); } else if(pathname=="/getlogin") //处理get方式请求 { var urlstr = url.parse(request.url).query; var jsondata = qs.parse(urlstr); var decodedata = decodeURIComponent(urlstr); console.log(urlstr); console.log(jsondata); console.log(decodedata); urlstr = decodedata; response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}); response.write(urlstr); response.end(); } else { response.writeHead(200,{"Content-Type":"text/plain"}); response.write("error"); response.end(); } }
知识点:
1.node创建一个简单的服务器
2.fs读取文件模块
3.url模块
4.解析url的querystring模块
有兴趣的可以参看api这里就不一一细说了