get请求和post请求

url模块给get请求用,更方便

  因为url模块的parse模块直接传入请求参数就行了,url.parse(req.url,true)
querystring模块给post请求用,更方便

  因为post请求接收到的参数组合成完整参数时,把该参数直接传入到querystring模块的parse方法中即可,querystring.parse(参数)

get请求
  get请求参数是一次传输完成,无需写监听事件

  

const http = require("http");
const url = require("url");
// 输入网址  http://localhost:8900/abc?name=zs&age=12
let server = http.createServer(function(req,res) {
    console.log(url.parse(req.url,true).query);
  
});
server.listen(8900);

 

post请求
  post请求参数的传输原理:post请求的参数是分段传输的,把参数拆分成若干段,然后一段一段传输给服务器
  服务器接收post请求:post请求需要监听数据传输过程,监听两个事件:数据事件和结束事件
  post请求接收过程:
    1、post请求,需要请求req监听“data”和“end”事件
      ata事件接收一段段的二进制参数,放进数组中
      end事件把一段段二进制参数组合一下,转化成参数

  

const http = require("http");
const querystring = require("querystring");
let server = http.createServer(function(req,res) {
    let arr = [];
    req.on("data",function(buffer) {
        arr.push(buffer);
    });
    req.on("end",function(){
        let buffer =  Buffer.concat(arr);
        console.log(buffer.toString());
        let post = querystring.parse(buffer.toString());
        console.log(post);
    });
});
server.listen(8900);

 


请求处理请求
  先判断请求方式,在判断路径

 

posted on 2019-02-18 11:32  悬剑  阅读(140)  评论(0)    收藏  举报

导航