zoukankan      html  css  js  c++  java
  • nodeJs学习-04 POST数据请求,分段发送,分段接收

    const http = require("http");
    const querystring= require('querystring');
    
    http.createServer(function(req,res){
      //post —— req
        // POST很大,会分段发送,分段接收
            // data - 有一段数据到达触发(多次)
            // end - 数据全部到达触发(一次)
      
      var str = '';   //存放数据
      req.on('data',function(data){
        console.log("接收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)

    案例:post和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 POST = querystring.parse(str);
          /*
          url - 要什么
          GET - get数据
          POST - post数据
          */
          console.log(url,GET,POST);
              // 当为post请求时,GET为空     /aaa {} { userName: 'post', pass: 'daf', content: 's' }
              // 当为get请求时,POST为空    /aaa { userName: 'afdaf', pass: 'dafsaf', content: 'adsf' } {}
        });
    
    
        //文件请求
        var file_name = "section05/www"+ url;
        fs.readFile(file_name,function(err,data){
          console.log('文件'+file_name);
          if(err){
            res.write('404')
          }else{
            res.write(data)
          };
          res.end();
        })
    
    }).listen(8081);
  • 相关阅读:
    PowerDesigner中利用数据库表反向生成PDM(jdk必须是32位)
    Struts2 Web Project 实现中文、英语的切换
    一张图解决Struts2添加源码
    Struts2配置文件struts.xml的编辑自动提示代码功能
    Hibernate多对一(注解)
    SQL Server 日期和时间函数
    ORACLE日期时间函数大全
    ORACLE中函数MONTHS_BETWEEN的使用
    SQL经典面试题及答案
    SQL数据库面试题以及答案
  • 原文地址:https://www.cnblogs.com/LChenglong/p/11585705.html
Copyright © 2011-2022 走看看