node.js 接收post请求


使用data和end事件来获取post数据,

相关阅读: 与

代码如下:

[javascript]

  1. var http = require('http');  
  2. var server = http.createServer();  
  3. var querystring = require('querystring');  
  4. var firstPage = function(res){  
  5.     res.writeHead(200, {'Content-Type''text/html'});  
  6.     var html = '<html><body>'+  
  7.         '<form action="/login" method="post">'+  
  8.         'name:<input type="text" name="name"> </br>'+  
  9.         'password:<input type="password" name="pwd"></br>'+  
  10.         '<input type="submit" value="login">'+  
  11.         '</form>'+  
  12.         '</body></html>';  
  13.     res.end(html);  
  14. }  
  15.   
  16. var login = function(req, res) {  
  17.     var info ='';  
  18.     req.addListener('data'function(chunk){  
  19.         info += chunk;  
  20.      })  
  21.     .addListener('end'function(){  
  22.         info = querystring.parse(info);  
  23.         if(info.name == 'a' && info.pwd =='1'){  
  24.             res.end('login success ' + info.name);  
  25.         }else{  
  26.             res.end('login failed ' + info.name);  
  27.         }  
  28.      })  
  29. }  
  30.   
  31. var requestFunction = function (req, res){  
  32.     if(req.url == '/'){  
  33.         return firstPage(res);  
  34.     }  
  35.     if(req.url == '/login'){  
  36.         if (req.method != 'POST'){  
  37.             return;  
  38.         }  
  39.         return login(req, res)  
  40.     }  
  41. }  
  42.   
  43. server.on('request',requestFunction);  
  44. server.listen(1337, "127.0.0.1");  
  45.   
  46. console.log('Server running at http://127.0.0.1:1337/');  

以上代码实现了一个登录验证用户,将以上代码保存到 example4.js

cmd键入 node example4.js


浏览器地址栏键入 http://127.0.0.1:1337/


如果输入name:a password:1 点击login



如果输入name:a password:2 点击login



该例子 from使用的是默认的application/x-www-form-urlencoded.

相关内容