• Vue基础——Vue前端交互


    目标:
      能够说出什么是前后端交互模式
      能够说出Promise的相关概念和用法
      能够使用fetch进行接口调用
      能够使用axios进行接口调用
      能够使用async/await方式调用接口
      能够基于后台接口实现案例
    目录:
      前后端交互模式
      Promise用法
      接口调用-fetch用法
      接口调用-axios用法
      接口调用async/await用法
      基于接口的案例

    1、前后端交互模式
    1.1、接口调用方式
      原生Ajax
      基于jQuery的Ajax
      fetch
      axios
    1.2、URL地址格式
    传统形式的URL
      格式:schema://host:port/path?query#fragment
        schema:协议。例如http、https、ftp等
        host:域名或IP地址
        port:端口,http默认端口80,可以省略
        path:路径,例如/abc/a/b/c
        query:查询参数,例如uname=lisi&age=12
        fragment:锚点(哈希Hash),用于定位页面的某个位置
      符合规则的URL:
        http://www.baidu.com
        http://www.baidu.com/java/web
        http://www.baidu.com/java/web?flag=1
        http://www.baidu.com/java/web?flag=1#function
    Restful形式的URL
      HTTP请求方式
        GET 查询
        POST 添加
        PUT 修改
        DELETE 删除
      符合规则的URL地址
        http://www.baidu.com/books GET
        http://www.baidu.com/books POST
        http://www.baidu.com/books/123 PUT
        http://www.baidu.com/books/123 DELETE

    2、Promise用法
    2.1、异步调用
    异步调用效果分析
      定时任务
      Ajax
      事件函数
    多次异步调用的依赖分析
      多次调用的结果顺序不确定
      异步调用结果如果存在依赖需要嵌套
    2.2、Promise概述
    Promise是异步编程的一种解决方案,从语法上讲,Promise是一个对象,从它可以获取异步操作的消息。
    使用Promise的优点:
      可以避免多层异步调用嵌套问题(回调地狱)
      Promise对象提供了简洁的API,使得控制异步操作更加容易
    2.3、Promise基本用法
    实例化Promise对象,构造函数中传递函数,该函数中用于处理异步任务
    resolve和reject两个参数用于处理成功和失败的两种情况,并通过p.then获取处理结果

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

    2.4、基于Promise处理Ajax请求
    处理原生Ajax

    function queryData(){
        return new Promise(function(resolve,reject){
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState != 4) return;
                if(xhr.status == 200){
                    resolve(xhr.responseText)
                }else{
                    reject('出错了');
                }
            }
            xhr.open('get','/data');
            xhr.send(null);
        })
    }

    发送多次Ajax请求

    queryData()
    .then(function(data){
        return queryData();
    })
    .then(function(data){
        return queryData();
    })
    .then(function(data){
        return queryData();
    })

    2.5、then参数中的函数返回值
    返回Promise实例对象
      返回的该实例对象会调用下一个then
    返回普通值
      返回的普通值会直接传递给下一个then,通过then参数中函数的参数接收该值
    2.6、Promise常用的API
    实例方法
      p.then() 得到异步任务的正确结果
      p.catch() 获取异常信息
      p.finally() 成功与否都会执行(尚且不是正式标准)
      语法结构:

    queryData()
    .then(function(data){
        console.log(data);
    })
    .catch(function(data){
        console.log(data);
    })
    .finally(function(){
        console.log('finished');
    })

    对象方法
      Promise.all()并发处理多个异步任务,所有任务都执行完成才能得到结果
      Promise.race()并发处理多个任务,只要有一个任务完成就能得到结果

    Promise.all([p1,p2,p3]).then((result) => {
        console.log(result)
    })
    Promise.race([p1,p2,p3]).then((result) => {
        console.log(result)
    })

    3、接口调用-fetch用法
    3.1、概述
    基本特性
      更加简单的数据获取方式,功能更强大,更灵活,可以看作是xhr的升级版
      基于Promise实现
    语法结构

    fetch(url).then(fn2)
                  .then(fn3)
                  ...
                  .catch(fn)

    3.2、fetch的基本用法

    fetch('/abc').then(data => {
        //text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
        return data.text();
    }).then(ret => {
        //注意:这里得到的才是最终的数据
        console.log(ret);
    })

    3.3、fetch2请求参数
    常用配置选项
      method(String):HTTP请求方法,默认为GET(GET,POST,PUT,DELETE)
      body(String):HTTP的请求参数
      headers(Onject):HTTP的请求头,默认为{}

    fetch('/abc',{
        method:'get'
    }).then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret);
    })

    GET请求方式的参数传递
      传统的URL

    fetch('/abc?id=123').then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret)
    })

      Restful形式的URL

    fetch('/abc/123',{
        method:'get'
    }).then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret);
    })

    DELETE请求方式的参数传递

    fetch('/abc/123',{
        method:'delete'
    }).then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret);
    })

    POST请求方式的参数传递
      字符串方式传递参数

    fetch('/books',{
        method:'post',
        body:'uname=lisi&pwd=123',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }).then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret);
    })

      json方式传递参数

    fetch('/books',{
        method:'post',
        body:JOSN.stringify({
            uname:'lisi',
            age:12
        }),
        headers:{
            'Content-Type':'application/json'
        }
    }).then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret);
    })

    PUT请求方式的参数传递

    fetch('/books/123',{
        method:'put',
        body:JOSN.stringify({
            uname:'lisi',
            age:12
        }),
        headers:{
            'Content-Type':'application/json'
        }
    }).then(data => {
        return data.text();
    }).then(ret => {
        console.log(ret);
    })

    4、接口调用-axios用法
    4.1、axios的基本特性
    axios是一个基于Promise用于浏览器和node.js的HTTP客户端。
    它具有以下特征:
      支持浏览器和node.js
      支持Promise
      能拦截请求和相应
      自动转换json数据
    4.2、axios的基本用法

    axios.get('/data').then(ret => {
        //data属性名称是固定的,用于获取后台响应的数据
        console.log(ret.data);
    })

    4.3、axios的常用API
    get:查询数据
    post:添加数据
    put:修改数据
    delete:删除数据
    4.4、axios的参数传递
    GET传递参数
      通过url传递参数
      通过params选项传递参数
      传统的url形式

    axios.get('/adata?id=123').then(ret => {
        console.log(ret.data);
    })

      Restful形式的URL

    axios.get('/adata/123').then(ret => {
        console.log(ret.data);
    })

      params方式

    axios.get('/adata',{
        params:{
            id:123
        }
    }).then(ret => {
        console.log(ret.data);
    })

    DELETE传递参数
      通过url传递参数
      通过params选项传递参数
      传统的url形式

    axios.delete('/adata?id=123').then(ret => {
        console.log(ret.data);
    })

      Restful形式的URL

    axios.delete('/adata/123').then(ret => {
        console.log(ret.data);
    })

      params方式

    axios.delete('/adata',{
        params:{
            id:123
        }
    }).then(ret => {
        console.log(ret.data);
    })

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

    axios.post('/adata',{
        uname:'tom',
        pwd:123
    }).then(ret => {
        console.log(ret.data);
    })

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

    const params = new URLSearchParams();
    params.append('params1','value1');
    params.append('params2','value2');
    axios.post('/adata',params}).then(ret => {
        console.log(ret.data);
    })

    PUT传递参数
      参数传递方式与POST类似

    axios.put('/adata/123',{
        uname:'tom',
        pwd:123
    }).then(ret => {
        console.log(ret.data);
    })

    4.5、axios的响应结果
    响应结果的主要属性
      data:实际响应回来的数据
      headers:响应头信息
      status:响应状态码
      statusText:响应状态信息
    4.6、axios的全局配置
      axios.default.timeout = 3000;//超时时间
      axios.default.baseURL = 'http://localhost:3000/app';//默认地址
      axios.default.headers['mytoken'] = 'asddwefwefwefewfefwefwe';//设置请求头
    4.7、axios拦截器
    请求拦截器
      在请求发出之前设置一些信息

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

    响应拦截器
      在获取数据之前对数据做一些加工处理

    //添加一个响应拦截器
    axios.interceptors.response.use(function(res){
        //在这里对返回的数据进行处理
        return res;
    },function(err){
        //处理响应的错误信息
        console.log(err);
    })

    5、接口调用-async/await用法
    5.1、async/await的基本用法
    async/await是ES7引入的新语法,可以更加方便的进行异步操作
    async关键字用于函数上(async函数的返回值是Promise实例对象)
    await关键字用于async函数中(await可以得到异步的结果)

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

    5.2、async/await处理多个异步请求
    多个异步请求的场景

    async function queryData(id){
        const info = await axios.get('/async1');
        const ret = await axios.get('async2?info='+info.data);
        return ret;
    }
    queryData.then(ret=>{
        console.log(ret);
    })
  • 相关阅读:
    推荐下自己的开源框架:DataMapFramework
    真的能无师自通吗?JAVA学习指导系列
    再回首,工作的第一个十年
    2个DataSet中的数据传递问题,请高手们多多指教。
    数据结构小结
    CDQZ_Training 2012524 词编码
    PowerDesigner显示Comment注释
    DDD基本元素
    使用FluorineFx.NET更新FMS中的SharedObject
    如何取消页面缓存
  • 原文地址:https://www.cnblogs.com/michealyang/p/13717008.html
Copyright © 2020-2023  润新知