前端交互你不知道的方法

前言:

作为一个前端程序员,我们一定要熟悉前端发送请求的各种方法,接下来就由本人来给大家介绍一下几种前端发送请求的方法。


发送请求的几种方式:

  • 原生 ajax
  • 基于Jquery的ajax
  • fetch
  • axios

URL地址格式:

如果我们想要前端发送请求,就必须先了解URL地址的格式,否则我们可能会发送错误的URL地址,导致请求失败!

传统形式URL:

格式:schema://host:port/path?query#fragment

  • schema:协议,例如 http ftp等
  • host: 域名或者ip地址
  • port:端口,http默认80
  • path:路径, 如 /abc/ac/b
  • query: 查询参数,例如 uname=list&age=11
  • fragment:锚点(哈希Hash),用于定位页面某个位置

Restful形式的URL:

通过使用相同的接口进行资源的访问。接口应该使用标准的HTTP方法如GET,PUT和POST,并遵循这些方法的语义,简而言之就是请求的地址都是一样的,但是可能跟的参数和请求方式不一样。

Http请求格式:

  •  Get 查询
  •  Post 添加
  •  PUT 修改
  •  DELETE 删除

原生Ajax:

 <script>
    function queryData(url) {
      var p = new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState != 4) {
            return;
          }
          if (xhr.readyState == 4 && xhr.status == 200) {
            resolve(xhr.responseText);
          } else {
            reject('服务器错误');
          }
        }
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }

    queryData('http://localhost:3000/data').then(function (data) {
      console.log(data);
    }).catch(function (info) {
      console.log(info);
    });
  </script>

发送多次ajax请求:

queryData('http://localhost:3000/data')
      .then(function (data) {
        console.log(data);
        return queryData('http://localhost:3000/data1');
      })
      .then(function (data) {
        console.log(data);
        return queryData('http://localhost:3000/data2');
      })
      .then(function (data) {
        console.log(data);
      });

fetch概述:

基本特性:

  • 更加简单的数据获取方式,更能更加强大,更加灵活,可以看做xhr的升级版
  • 基于Promise实现

语法结构:

  <script>
    fetch('http://localhost:3000/fdata').then(function (data) {
      // text() 属于 fetchAPI的一部分,返回一个promise实例对象,用于获取后台返回的数据
      return data.text();
    })
      .then(function (data) {
    //这里是最终获得的数据
        console.log(data);
      })
  </script>

常用配置选项:

  • method(String): HTTP请求方法,默认为 get(get,post,put,delete)
  • body(String):HTTP的请求参数
  • headers(Object): HTTP的请求头,默认为{}

GET请求方式传递参数:

  <script>
    fetch('http://localhost:3000/books?id=12345678', {
      method: 'get'
    })
      .then(function (data) {
        return data.text();
      })
      .then(function (data) {
        console.log(data);
      });


    fetch('http://localhost:3000/books/12345678', {
      method: 'get'
    })
      .then(function (data) {
        return data.text();
      })
      .then(function (data) {
        console.log(data);
      })
  </script>

DELETE请求方式传递参数:

  <script>
        fetch('http://localhost:3000/books/666', {
      method: 'delete'
    })
      .then(function (data) {
        return data.text();
      })
      .then(function (data) {
        console.log(data);
      })
  </script>

POST请求方式传递参数:

 <script>

    //post 参数为 字符串
    fetch('http://localhost:3000/books', {
      method: 'post',
      body: 'uname=sss&pwd=666',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
      .then(function (data) {
        return data.text();
      })
      .then(function (data) {
        console.log(data);
      });

  </script>
<script>
   //Post 参数是json字符串
        fetch('http://localhost:3000/books', {
      method: 'post',
      body: JSON.stringify({
        uname: '张三',
        pwd: '456'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
 </script>

PUT请求方式的参数传递:

<script>    
        fetch('http://localhost:3000/books/123', {
      method: 'put',
      body: JSON.stringify({
        uname: '张三',
        pwd: '666'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>

fetch响应结果:

响应数据格式:

  • text(): 将返回体处理成字符串类型
  • json():  返回结果和JSON.parse(responseText)一样
<script>
   //返回结果是对象
    fetch('http://localhost:3000/json').then(function (data) {
      return data.json();
    }).then(function (data) {
      console.log(data);
    });
    
    //经过调用 json.parse()方法, 将字符串转换成对象
    fetch('http://localhost:3000/json').then(function (data) {
      return data.text();
    }).then(function (data) {
      console.log(JSON.parse(data));
    });

  </script>

接口调用- axios用法

axios的基本特性:

一个基于Promise用于浏览器和node.js的HTTP客户端。

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截响应和请求
  • 自动转换JSON数据

axios基本用法:

  <script>
    axios.get('http://localhost:3000/adata').then(function (res) {
      //data属性是固定用法,用于获取后台实际数据
      console.log(res.data);
      console.log(res);
    })
  </script>

axios常用API:

get: 查询数据

  • 通过URL传递参数
  • 通过params选项传递参数
    axios.get('http://localhost:3000/axios?id=123').then(function (ret) {
      console.log(ret.data)
    });

        //resuful风格
    axios.get('http://localhost:3000/axios/123').then(function (ret) {
      console.log(ret.data)
    })

     //params选项传递参数
    axios.get('http://localhost:3000/axios', {
      params: {
        id: 789
      }
    }).then(function (ret) {
      console.log(ret.data)
    });

post: 添加数据

通过选项传递参数(默认传递json格式的数据)

    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function (ret) {
      console.log(ret.data)
    })

通过URLSearchParams传递参数(application/x-www-form-rlencoded)

    var params = new URLSearchParams();
    params.append('uname', 'zhangsan');
    params.append('pwd', '111');
    axios.post('http://localhost:3000/axios', params).then(function(ret){
      console.log(ret.data)
    })

put:修改数据

// axios put 请求传参
    axios.put('http://localhost:3000/axios/123', {
      uname: 'lisi',
      pwd: 123
    }).then(function (ret) {
      console.log(ret.data)
    })

delete: 删除数据

    axios.delete('http://localhost:3000/axios?id=123').then(function (ret) {
      console.log(ret.data)
    });

        //resuful风格
    axios.delete('http://localhost:3000/axios/123').then(function (ret) {
      console.log(ret.data)
    })

        // axios delete 请求传参
    axios.delete('http://localhost:3000/axios', {
      params: {
        id: 111
      }
    }).then(function (ret) {
      console.log(ret.data)
    })

axios的响应结果: 

响应结果的主要属性:

  • data:实际响应回来的数据
  • headers:响应头信息
  • status:响应状态码
  • statusText:响应状态信息

axios的全局配置:

axios.defaults.timeout = 3000; //超时时间

axios.defaults.baseURL = 'http://localhost:3999/app'; //默认地址

axios.defaults.headers['mytoken'] = 'slkfaskl33sfxv'; //设置请求头

axios拦截器:

请求拦截器:

image.png

    /*
      axios拦截器
    */
    axios.interceptors.request.use(function(config) {
      console.log(config.url)
      config.headers.mytoken = 'nihao';
      return config;
    }, function(err){
      console.log(err)
    })

响应拦截器:

image.png

    axios.interceptors.response.use(function(res) {
      // console.log(res)
      var data = res.data;
      return data;
    }, function(err){
      console.log(err)
    })

总结:

前端交互无非就是使用原生Ajax、使用fetch、使用封装好的axios等办法,我们不仅要能使用,更要去了解里边的原理,本篇先讲的是基本使用,后期会讲解一下原理。

猜你喜欢

转载自blog.csdn.net/wjf1997/article/details/105622664