• 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');  
    });
  • 相关阅读:
    二分搜索树的深度优先遍历和广度优先遍历
    数据结构与算法之非比较排序【Java】
    数据结构与算法之比较排序【Java】
    像素 转换 px dp
    Toast
    MySQL丶auto_increment
    MariaDB · 性能优化 · Extended Keys
    加唯一索引怎么会导致丢数据
    语句执行错误一· Count(Distinct) ERROR
    innodb参数 &#183; innodb_flush_log_at_trx_commit
  • 原文地址:https://www.cnblogs.com/lengyuhong/p/2488886.html
Copyright © 2020-2023  润新知