Vue(3)

2020-06-16  本文已影响0人  晚月川

前后端交互

  1. 前后端交互模式
  2. Promise用法
  3. 接口调用-fetch用法
  4. 接口调用-async/await用法
  5. 接口调用-async/await用法

接口调用方式

URL地址格式

  1. 传统形式的URL

    • 格式:schema://host:port/path?query#fragment
      1. schema:协议。例如http、https、ftp等
      2. host:域名或者IP地址
      3. port:端口。http默认端口80,可以省略
      4. path:路径。例如/abc/a/b/c
      5. query:查询参数。例如uname=zhangsan&age=12
      6. fragment:锚点(哈希Hash),用于定位页面的某个位置
  2. Restful形式的URL

    • http请求方式
      1. GET:查询
      2. POST:添加
      3. PUT:修改
      4. DELETE:删除

Promise用法

Promise概述:Promise是异步编程的一种解决方案,从语法上将:从它可以获取异步操作的消息

使用Promise主要有以下好处

  • 可以避免多层异步调用嵌套问题(回调地狱)
  • Promise对象提供了简洁的API,使得控制异步操作更加容易
  1. 实例化Promise对象,构造函数中传递函数,该函数用于处理异步任务

  2. resolvereject两个参数用于处理成功和失败两种情况,并通过p.then获取处理结果

    var p = new Promise(function(resolve, rejected) {
        // 成功时调用  resolve()
        // 失败时调用  rejected()
    });
    p.then(function(ret){
        // 从resolve得到正常结果
    }, function(ret){
        // 从rejected得到错误信息
    })
    

基于Promise处理Ajax请求

// 处理原生Ajax
function queryData(){
    var p = new Promise(function(resolve, rejected){
        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;
}

Promise常用的API

  1. 实例方法

    • p.then() 得到异步任务的正确结果
    • p.catch() 获取异常信息
    • p.finally() 成功与否都会执行(尚且不是正式标准)
    queryData()
        .then(function(data){
            console.log(data);
        })
        .catch(function(data){
            console.log(data);
        })
        .finally(function(){
            console.log('finished');
        });
    
  2. 对象方法

    • Promise.all() 并发处理多个异步任务,所有的任务都执行完成才能得到结果
    • Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果
    Promise.all([p1,p2,p3]).then((result) => {
        console.log(result);
    });
    Promise.race([p1,p2,p3]).then((result) => {
        console.log(result);
    })
    

接口调用-fetch

  1. fetch 请求参数

    • 常用配置项

      • method(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)
      • body(String):HTTP的请求参数
      • headers(Object):HTTP请求头,默认为{}
      fetch('/abc', {
          method: 'get'
      }).then(data=>{
          return data.text();
      }).then(ret=>{
          // 这里才是最终得到的数据
          console.log(ret);
      })
      
    • GET请求方式的参数传递

        ```javascript
        fetch('/abc?id=123').then(data=>{
            return data.text();
        }).then(ret=>{
        // 这里才是最终得到的数据
        console.log(ret);
        })
        ```
      
        ```javascript
        fetch('/abc', {
            method: 'get'
        }).then(data=>{
            return data.text();
        }).then(ret=>{
            // 这里才是最终得到的数据
            console.log(ret);
        })
        ```
      
    • DELETE请求方式的参数传递

      fetch('/abc', {
          method: 'delete'
      }).then(data=>{
          return data.text();
      }).then(ret=>{
          // 这里才是最终得到的数据
          console.log(ret);
      })
      
    • POST请求的参数传递

      fetch('/books', {
          method: 'post',
          body: 'uname=zhangsan&pwd=123',
          headers: {
              'Content-Type': 'application/json'
          }
      }).then(data=>{
          return data.text();
      }).then(ret=>{
          console.log(ret);
      });
      
      fetch('/books', {
          method: 'post',
          body: JSON.stringify({
              uname: 'zhangsan',
              age: 12
          }),
          headers: {
              'Content-Type': 'application/json'
          }
      }).then(data=>{
          return data.text();
      }).then(ret=>{
          console.log(ret);
      });
      
    • PUT请求参数的传递

      fetch('/books', {
          method: 'put',
          body: JSON.stringify({
              uname: 'zhangsan',
              age: 12
          }),
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
          }
      }).then(data=>{
          return data.text();
      }).then(ret=>{
          console.log(ret);
      });
      
  2. fetch 响应结果

    • text():将返回体处理成字符串类型
    • json():返回结果和JSON.parse(response)一样
    fetch('/abc').then(data=>{
        // return data.text();
        return data.json();
    }).then(ret=>{
        console.log(ret);
    })
    

接口调用-axios

axios(官网:https://github.com/axios/axios) 是一个基于promise用于浏览器和node.js的HTTP客户端

axios常用的API

axios的参数传递

axios 的响应结果

axios 拦截器

  1. 请求拦截器

    • 在请求发出之前设置一些信息
    // 添加一个请求拦截器
    axios.interceptors.request.use(function(config) {
        // 在请求之前进行一些信息设置
        return config;
    },function(err) {
        // 处理响应的错误信息
    });
    
  2. 响应拦截器

    • 在获取数据之前对数据做一些加工处理
    // 添加一个响应拦截器
    axios.interceptors.response.use(function(res) {
        // 在这里对返回的数据进行处理
        return config;
    },function(err) {
        // 处理响应的错误信息
    });
    

接口调用-async/await 的基本用法

async function queryData(id) {
    const ret = await axios.get('/data');
    return ret;
}
queryData.then(ret=>{
    console.log(ret)
})

async/await处理多个异步请求

// 多个异步请求的场景
async function queryData(id) {
    const info = await axios.get('/async');
    const ret = await axios.get(`async2?info=` + info.data);
    return ret;
}
queryData.then(ret=>{
    console.log(ret);
})
上一篇 下一篇

猜你喜欢

热点阅读