nodeJs学习-03 GET数据请求,js拆解/querystring/url

原生JS解析参数:

const http = require('http');
http.createServer(function(req,res){
  var GET = {};   //接收数据容器

  if(req.url.indexOf('?')!= -1){      //因为req.url中可能没有数据,或者是favicon.ico,为避免报错,我们要进行判断
    //req获取前台请求数据
    // console.log(req.url);   //?userName=dsdf&pass=sdfsf
    var arr = req.url.split("?");
    var url = arr[0];

    // arr[1] => 数据:userName=dsdf&pass=sdfsf
    var arr2 = arr[1].split('&');     // => ['userName=dsdf',pass=sdfsf]
    for(var i=0;i<arr2.length;i++){
      var arr3 = arr2[i].split('=');
      //arr3[0] => 名字  'usrName';
      //arr[1] => 数据    '密码'
      GET[arr3[0]] = arr3[1];
    }

  }else{
    var url = req.url;
  };
  console.log(url,GET);     //{userName:'name','pass':'23424'}

  //!!!因为要解析GET参数比较麻烦,所以node有专门的模块:querystring
  // querystring 模块提供了一些实用函数,用于解析与格式化 URL 查询字符串。
  res.write('aaa');
  res.end();
}).listen(8088);

querystring解析参数

//因为要解析GET参数比较麻烦,所以node有专门的模块:querystring
  // querystring 模块提供了一些实用函数,用于解析与格式化 URL 查询字符串。

const queryString=require('querystring');

var json= queryString.parse('userName=blue&pass=123445&age=18');
console.log(json);      //{ userName: 'blue', pass: '123445', age: '18' }

url解析参数:

const urlLib=require('url');
var obj = urlLib.parse('http://www.zihe8888.com/index?userName=blue&pass=123445&age=18');
console.log(obj);

// Url {
//   protocol: 'http:',
//   slashes: true,
//   auth: null,
//   host: 'www.zihe8888.com',
//   port: null,
//   hostname: 'www.zihe8888.com',
//   hash: null,
//   search: '?userName=blue&pass=123445&age=18',
//   query: 'userName=blue&pass=123445&age=18',
//   pathname: '/index',
//   path: '/index?userName=blue&pass=123445&age=18',
//   href: 'http://www.zihe8888.com/index?userName=blue&pass=123445&age=18' }

var obj = urlLib.parse('http://www.zihe8888.com/index?userName=blue&pass=123445&age=18',true);      //带上参数true,就会自动解析query为对象了
console.log(obj);
// Url {
//   protocol: 'http:',
//   slashes: true,
//   auth: null,
//   host: 'www.zihe8888.com',
//   port: null,
//   hostname: 'www.zihe8888.com',
//   hash: null,
//   search: '?userName=blue&pass=123445&age=18',
//   query: { userName: 'blue', pass: '123445', age: '18' },    //数据部分
//   pathname: '/index',      //地址部分
//   path: '/index?userName=blue&pass=123445&age=18',
//   href: 'http://www.zihe8888.com/index?userName=blue&pass=123445&age=18' }

案例:最简单的解析方法

// 最简单的解析方法!!!!!

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

http.createServer(function(req,res){
  var obj = urlLib.parse(req.url,true);
  var url = obj.pathname;   //文件名称
  var GET = obj.query;
  console.log(GET);
  console.log(url);

  res.write('aaa');
  res.end();

}).listen(8088);
原文地址:https://www.cnblogs.com/LChenglong/p/11571406.html