nodeJs learning -04 POST request data, the transmission segment, the segment receiver

the require HTTP = const ( "HTTP" ); 
const QueryString = the require ( 'QueryString' ); 

http.createServer ( function (REQ, RES) {
   // POST - REQ 
    // big the POST, will be sent by segment, segment receiving 
        // data - some data reaches the trigger (multiple) 
        // End - all data reaches the trigger (a) 
  
  var STR = '';    // store data 
  req.on ( 'data', function (data) { 
    Console. log ( "reception time data" ); 
    STR + = data; 
  }); 

  req.on ( 'End', function () {
     // console.log(str);       //userName=aaa&pass=fdsalfjdsl&content=lsafjdla70455
    var postData = querystring.parse(str);
    console.log(postData);   // { userName: 'fsadsafd',  pass: 'adsfsafdsa',  content: 'fasdfasfzxvxcbvasgasdgsad' }
  });

  res.end();

}).listen(8081)

 

 

Case: post and get

const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlLib = require('url');



var server = http.createServer(function(req,res){
    //GET数据
    var obj = urlLib.parse(req.url,true);
    var url = obj.pathname;
    const GET = obj.query;


    // POST数据
    var str = '';
    req.on('data',function(data){
      str+=Data; 
    }); 

    req.on ( 'End', function () { 
      const the POST = querystring.parse (STR);
       / * 
      URL - to what 
      GET - get data 
      POST - post data 
      * / 
      the console.log (URL, the GET , POST); 
          // when to post requests, gET empty / AAA {} {the userName: 'post', Pass: 'DAF', Content: 'S'} 
          // when to get request, POST empty / the userName {AAA: 'afdaf', Pass: 'dafsaf', Content: 'ADSF' {}} 
    }); 


    // file request 
    var file_name = "section05 / WWW" + URL; 
    fs.readFile (file_name, function (ERR, Data) { 
      Console.log ( 'file' +file_name);
      if(err){
        res.write('404')
      }else{
        res.write(data)
      };
      res.end();
    })

}).listen(8081);

 

Guess you like

Origin www.cnblogs.com/LChenglong/p/11585705.html