nodejs的get和post服务

    在web服务中,提交表达和数据时,get和post是非常常用的两种服务。现用nodejs实现这两个服务。

一、get操作

app.html:

<html>
  <head>
    <title>登陆页面</title>
  </head>
  <body>
    <form action="check" method="get">
      <p>First name: <input type="text" name="fname" /></p>
      <p>Last name: <input type="text" name="lname" /></p>
      <input type="submit" value="Submit" />
    </form>
  </body>
</html> 

 

app.js

var http = require('http');
var urllib = require('url');
var fs = require('fs');

var html = fs.readFileSync('./app.html');

var app = http.createServer(function(req, res){
  var params = urllib.parse(req.url, true);
  if (params.pathname === '/login') {
    res.end(html);
  } else if (params.pathname === '/check') {
    var params = urllib.parse(req.url, true);
    res.end(JSON.stringify(params.query));
  }
});

app.listen(5678, function(){
  console.log('server is listening on 5678');  
});

 

二、post操作

post的实现相对比较繁琐,可以特别注意下buffer.copy这个函数

app.html:

<html>
  <head>
    <title>登陆页面</title>
  </head>
  <body>
    <form action="check" method="post">
      <p>First name: <input type="text" name="fname" /></p>
      <p>Last name: <input type="text" name="lname" /></p>
      <input type="submit" value="Submit" />
    </form>
  </body>
</html> 

app.js:

var http = require('http');
var urllib = require('url');
var fs = require('fs');
var querystring = require('querystring');

var html = fs.readFileSync('./app.html');

var app = http.createServer(function(req, res){
  var params = urllib.parse(req.url, true);
  if (params.pathname === '/login') {
    res.end(html);
  } else if (params.pathname === '/check') {
    var chunks = [];
    var length = 0;
    var rows = null;
    req.on('data', function(data){
      chunks.push(data);
      length += data.length;
    }) 
    req.on('end', function(){
      var rows = new Buffer(length);
      var len = 0;
      for (var i = 0, il = chunks.length; i < il; i++) {
        chunks[i].copy(rows, len);
        len += chunks[i].length;
      }
      var args = querystring.parse(rows.toString());
      res.end(JSON.stringify(args));
    })
  }
  
});

app.listen(5678, function(){
  console.log('server is listening on 5678');  
});
posted @ 2012-05-07 21:37  lengyuhong  阅读(2698)  评论(0编辑  收藏  举报