标签:
首先我们在项目下创建一个表单,代码如下所示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>form表单测试</h1> <form name="index" action="/post" method="post"> <label>USER:<input type="text" name="user" ></label><br /> <label>PASS:<input type="text" name="password" ></label><br /> <label>EMAIL:<input type="text" name="email" ></label><br /> <label>ADDRESS:<input type="text" name="address" ></label><br /> <input type="submit" value="OK"> <input type="reset" value="重置"> </form> </body> </html>
上面的name是一定要有的,因为我们到时候是通过他来对表单进行访问的,然后开始编写index.js文件,代码如下所示:
var http = require(‘http‘), fs = require(‘fs‘), url = require(‘url‘), util = require(‘util‘), querystring = require(‘querystring‘); var server = http.createServer(function(req,res){ var pathname = url.parse(req.url).pathname; if(pathname == ‘/index‘){ var pageContent = fs.readFile(‘index.html‘,‘utf-8‘,function(err,data){ if(err){ console.log(‘Server error:111‘); }else{ res.writeHead(200,{"Content-Type":"text/html"}); res.write(data); res.end(); } }); }else if(pathname == ‘/post‘){ var post = ‘‘; req.on(‘data‘,function(chunk){ post += chunk; }); req.on(‘end‘,function(){ post = querystring.parse(post); res.writeHead(200,{"Content-Type":"text/html"}); res.write(‘user is ‘+ post.user + ‘<br />‘); res.write(‘password is ‘+ post.password + ‘<br />‘); res.write(‘email is ‘+ post.email + ‘<br />‘); res.write(‘address is ‘+ post.address); res.end(); }); }else{ res.writeHead(404,{"Content-Type":"text/plain"}); res.end(‘error:404‘); console.log(‘error‘); } }); server.listen(3323); console.log(‘@http://localhost:3323‘);
然互我们通过http://localhost:3323/index 这样的方法对她进行访问,效果如下所示:
点击提交过后即可获取到结果:
标签:
原文地址:http://www.cnblogs.com/leigood/p/5769406.html