GVKun编程网logo

vue之Promise、Fetch、Axios入门以及学习总结,涉及Express搭建接口(vue promise axios)

14

本文将介绍vue之Promise、Fetch、Axios入门以及学习总结,涉及Express搭建接口的详细情况,特别是关于vuepromiseaxios的相关信息。我们将通过案例分析、数据研究等多种方

本文将介绍vue之Promise、Fetch、Axios入门以及学习总结,涉及Express搭建接口的详细情况,特别是关于vue promise axios的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于11-利用Promise的图片异步加载 / Promise封装ajax,模拟axios / Promise的finally原理、ajax、axios、fetch、ajax、axios、fetch 之间的详细区别以及优缺点、ajax、axios、fetch之间的优缺点对比的知识。

本文目录一览:

vue之Promise、Fetch、Axios入门以及学习总结,涉及Express搭建接口(vue promise axios)

vue之Promise、Fetch、Axios入门以及学习总结,涉及Express搭建接口(vue promise axios)

基于Promise发送原生Ajax请求

 // 基于Promise发送原生Ajax请求
    function queryData(url) {
      //resolve请求成功的回调函数  reject请求失败的回调函数
      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;
    }

    // 发送多个ajax请求并且保证顺序
    queryData(''http://localhost:3000/data'')
      .then(function(data){
        console.log(data)
        return queryData(''http://localhost:3000/data1'');
      })
      //这里的then指向的是上面return的promise对象
      .then(function(data){
        console.log(data);
         return ''hello'';
      })
       //这里的then指向的是上面return返回新创建的promise对象
      .then(function(data){
        console.log(data)
      });

异步任务API
.then(function(data){})  任务成功执行的函数
.catch(function(error){})    任务出错执行的函数
.finally(function(){})  无论成功出错都会执行的函数
.race([a,b,..])  参数是一个数组,数组是promise对象,该方法是执行数组内所有的异步函数,返回最快执行完的一个promise对象结果
.all([a,b,..]) 参数是一个数组,数组是promise对象,该方法需要所有的异步函数执行完才会返回结果
 

var p1 = queryData(''http://localhost:3000/a1'');
    var p2 = queryData(''http://localhost:3000/a2'');
    var p3 = queryData(''http://localhost:3000/a3'');
    Promise.all([p1,p2,p3]).then(function(result){
      console.log(result)
    })
    Promise.race([p1,p2,p3]).then(function(result){
      console.log(result)
    })

异步函数返回的值是promise对象,如果希望得到返回的数据,可以使用async  await

Fetch(用法跟promise类似)

Fetch API是新的ajax解决方案 
Fetch会返回Promise fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象

//使用Express框架搭建服务器
const express = require(''express'')
const app = express()
// Express框架默认使用body-parser作为请求体解析中间件
const bodyParser = require(''body-parser'')
// 处理静态资源
app.use(express.static(''public''))
// 处理参数
app.use(bodyParser.json());
// false表示使用系统模块querystring来处理,也是官方推荐的,true即使用第三方模块
app.use(bodyParser.urlencoded({ extended: false }));

// 设置允许跨域访问该服务
app.all(''*'', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(''Access-Control-Allow-Methods'', ''PUT, GET, POST, DELETE, OPTIONS'');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header(''Access-Control-Allow-Headers'', ''Content-Type'');
  res.header(''Access-Control-Allow-Headers'', ''mytoken'');
  next();
});

//服务器端get请求接口一
app.get(''/fdata'', (req, res) => {
  res.send(''Hello Fetch!'')
})
 /*
    //客户端请求代码
    fetch(''http://localhost:3000/fdata'').then(function(data){
    // text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
      return data.text();
    }).then(function(data){
      console.log(data);
    })   
*/


//服务器端get请求接口二
app.get(''/books'', (req, res) => {
  // query是url的查询参数
  res.send(''传统的URL传递参数!'' + req.query.id)
})

/*
    //客户端请求代码
    //GET参数传递-传统URL
    fetch(''http://localhost:3000/books?id=123'', {
      method: ''get''
    })
      .then(function(data){
        //将返回值转换成字符串
        return data.text();
      }).then(function(data){
        // 输出123
        console.log(data)
      });
*/


//服务器端get请求接口三
app.get(''/books/:id'', (req, res) => {
  // params是参数名
  res.send(''Restful形式的URL传递参数!'' + req.params.id)
})

/*
    //客户端请求代码
    //GET参数传递-restful形式的URL
    fetch(''http://localhost:3000/books/456'', {
      method: ''get''
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服务器端delete请求接口
app.delete(''/books/:id'', (req, res) => {
  res.send(''DELETE请求传递参数!'' + req.params.id)
})

/*
    //客户端请求代码
    //DELETE请求方式参数传递
    fetch(''http://localhost:3000/books/789'', {
      method: ''delete''
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服务器端post请求接口一
app.post(''/books'', (req, res) => {
  //这里的body是经过解析中间件处理得到的
  res.send(''POST请求传递参数!'' + req.body.uname + ''---'' + req.body.pwd)
})


/*
    //客户端请求代码
    //POST请求传参
    fetch(''http://localhost:3000/books'', {
      method: ''post'',
      body: ''uname=lisi&pwd=123'',
      headers: {
        //这里一定要设置类型   类型为:''uname=lisi&pwd=123''格式
        ''Content-Type'': ''application/x-www-form-urlencoded''
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服务器端post请求接口二
app.put(''/books/:id'', (req, res) => {
  res.send(''PUT请求传递参数!'' + req.params.id + ''---'' + req.body.uname + ''---'' + req.body.pwd)
})

/*
    //客户端请求代码
    //POST请求传参
    fetch(''http://localhost:3000/books'', {
      method: ''post'',
      body: JSON.stringify({
        uname: ''张三'',
        pwd: ''456''
      }),
      headers: {
        //这里设置的参数类型是json格式
        ''Content-Type'': ''application/json''
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/


//服务器端put请求接口
app.put(''/books/:id'', (req, res) => {
  res.send(''PUT请求传递参数!'' + req.params.id + ''---'' + req.body.uname + ''---'' + req.body.pwd)
})

/*
    //客户端请求代码
    // PUT请求传参
    fetch(''http://localhost:3000/books/123'', {
      method: ''put'',
      body: JSON.stringify({
        uname: ''张三'',
        pwd: ''789''
      }),
      headers: {
        ''Content-Type'': ''application/json''
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
*/

Axios

基于promise用于浏览器和node.js的http客户端
支持浏览器和node.js 
支持promise 
能拦截请求和响应 
自动转换JSON数据 
能转换请求和响应数据 

axios基础用法 
get和 delete请求传递参数 
通过传统的url 以 ? 的形式传递参数 
restful 形式传递参数 
通过params 形式传递参数
 post 和 put 请求传递参数 
通过选项传递参数 
通过 URLSearchParams 传递参数

//服务器端get接口一
// query查询参数
app.get(''/axios'', (req, res) => {
  res.send(req.query.id)
})

/*
    //客户端get请求传参方式一
    axios.get(''http://localhost:3000/axios?id=123'').then(function(ret){
      console.log(ret.data)
    })
*/


//服务器端get接口二    params参数
app.get(''/axios/:id'', (req, res) => {
  res.send(req.params.id)
})

/*
    //客户端get请求方式二
    axios.get(''http://localhost:3000/axios/123'').then(function(ret){
      console.log(ret.data)
    })
*/

/*
    //客户端get请求方式三
    axios.get(''http://localhost:3000/axios'', {
      params: {
        id: 789
      }
    }).then(function(ret){
      console.log(ret.data)
    })
*/


//服务器端delete接口
app.delete(''/axios'', (req, res) => {
  res.send(req.query.id)
})

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


//服务器端post接口
app.post(''/axios'', (req, res) => {
  res.send(req.body.uname + ''---'' + req.body.pwd)
})

/*
    //客户端post请求方式一 json格式
    axios.post(''http://localhost:3000/axios'', {
      uname: ''lisi'',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })

    //客户端post请求方式二 字符串格式   通过URLSearchParams 传递参数
    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接口
app.put(''/axios/:id'', (req, res) => {
  res.send(req.params.id + ''---'' + req.body.uname + ''---'' + req.body.pwd)
})

/*
    //客户端post请求方
    axios.put(''http://localhost:3000/axios/123'', {
      uname: ''lisi'',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })
*/

axios 全局配置 

// 配置请求的基准URL地址
    axios.defaults.baseURL = ''http://localhost:3000/'';
    // 配置 超时时间 
    axios.defaults.timeout = 2500;
    // 配置请求头信息
    axios.defaults.headers[''mytoken''] = ''hello'';
    //因为配置的基准url地址,此处url不用重复写
    axios.get(''axios-json'').then(function(ret){
      console.log(ret.data.uname)
    })

axios 拦截器 
1、请求拦截器 
请求拦截器的作用是在请求发送前进行一些操作 
例如在每个请求体里加上token,统一做了处理如果以后要改也非常容易 
2、响应拦截器 
响应拦截器的作用是在接收到响应后进行一些操作 
例如在服务器返回登录状态失效,需要重新登录的时候,跳转到登录页

    // 请求拦截器 
    axios.interceptors.request.use(function(config) {
      // 任何请求都会经过这一步   在发送请求之前做些什么 
      //设置请求头信息
      config.headers.mytoken = ''nihao'';
      // 这里一定要return   否则配置不成功 
      return config;
    }, function(err){});

    // 响应拦截器 
    axios.interceptors.response.use(function(res) {
      //在此处可以对响应的内容做处理,如下将返回res的data内容。
      var data = res.data;
      return data;
    }, function(err){});

async 和 await 

async作为一个关键字放到函数前面 
任何一个 async 函数都会隐式返回一个 promise 
await 关键字只能在使用 async 定义的函数中使用 
await后面可以直接跟一个 Promise实例对象 
await函数不能单独使用 
async/await 让异步代码看起来、表现起来更像同步代

//服务器端接口
app.get(''/async1'', (req, res) => {
  res.send(''hello'')
})
app.get(''/async2'', (req, res) => {
  if(req.query.info == ''hello'') {
    res.send(''world'')
  }else{
    res.send(''error'')
  }
})

// 客户端请求方式
    async function queryData() {
      var info = await axios.get(''async1'');
      var ret = await axios.get(''async2?info='' + info.data);
      return ret.data;
    }
    queryData().then(function(data){
      console.log(data)
    })

 

 

 

 

11-利用Promise的图片异步加载 / Promise封装ajax,模拟axios / Promise的finally原理

11-利用Promise的图片异步加载 / Promise封装ajax,模拟axios / Promise的finally原理

Promise的图片异步加载其实就是利用了宏任务先执行,后执行微任务:

new Promise()的时候,Promise新建后就会立即执行

 

 利用这一特性,我们可以创建Promise对象的时候,创建image标签,然后再给img标签的 src赋值路径,这样在then的回调函数中,把其加入到盛放显示图片的盒子中,盒子中原来展示是一个缺省图,等到图片加载好了,就显示真正的图片:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <Meta charset="UTF-8">
 6     <Meta http-equiv="X-UA-Compatible" content="IE=edge">
 7     <Meta name="viewport" content="width=device-width, initial-scale=1.0">
 8     <title>Document</title>
 9 </head>
10 <style>
11     h1 {
12         display: block;
13     }
14 </style>
15 
16 <body>
17     <div id='Box'>
18         <h1>我是一张缺省图</h1>
19     </div>
20 </body>
21 
22 </html>
23 <style>
24 
25 </style>
26 <script>
27     var oBox = document.getElementById('Box');
28     var oH = document.querySelector('h1')
29 
30     function loadImageAsync(url) {
31         return new Promise(function(resolve, reject) {
32             var image = new Image();
33 
34             image.onload = function() {
35                 resolve(image);
36             };
37 
38             image.onerror = function() {
39                 reject(new Error('Could not load image at ' + url));
40             };
41 
42             image.src = url;
43         });
44     }
45     // 模拟一下异步加载图片
46     // 用setTimeoutm模拟ajax调用接口,获取接口返回的图片路径,然后传入函数中,函数中已经提前创建好了
47     // 图片标签。我们在.then的回调函数中自行决定插入div容器中做一些事,比如把缺省图隐藏掉
48     setTimeout(() => {
49         loadImageAsync('./lion.jpg').then(res => {
50             oH.style.display = 'none';
51             oBox.appendChild(res);
52         })
53     }, 1000)
54 </script>

 

 1秒后显示图片:


 

 Promise封装ajax

 

 1    function myAxios(url) {
 2         return new Promise((resolve, reject) => {
 3             let http = new XMLHttpRequest();
 4             http.open('GET', url)
 5             http.onreadystatechange = function() {
 6                 if (this.readyState !== 4) {
 7                     return
 8                 }
 9                 if (this.status === 200) {
10                     resolve(this.response)
11                 } else {
12                     reject(new Error(this.txt))
13                 }
14             }
15             http.send();
16         })
17     }
18 
19     myAxios('').then(res => {
20         // 拿到数据
21     }).catch(err => {
22         // 捕获错误
23     })

Promise的finally原理

 

 

 

ajax、axios、fetch

ajax、axios、fetch

jQuery ajax

$.ajax({
   type: ''POST'',
   url: url,
   data: data,
   dataType: dataType,
   success: function () {},
   error: function () {}
});

优缺点

  • 本身是针对MVC的编程,不符合现在前端MVVM的浪潮
  • 基于原生的XHR开发,XHR本身的架构不清晰,已经有了fetch的替代方案
  • JQuery整个项目太大,单纯使用ajax却要引入整个JQuery非常的不合理(采取个性化打包的方案又不能享受CDN服务

axios

axios({
    method: ''post'',
    url: ''/user/12345'',
    data: {
        firstName: ''Fred'',
        lastName: ''Flintstone''
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
  • 发送一个get请求
//格式一
axios.get(''/user?ID=12345'')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 格式二
axios.get(''/user'', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 发送post请求
axios.post(''/user'', {
    firstName: ''Fred'',
    lastName: ''Flintstone''
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

优缺点

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截请求和响应
  • 能转换请求和响应数据
  • 能取消请求
  • 自动转换JSON数据
  • 浏览器端支持防止CSRF(跨站请求伪造)

fetch

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

优缺点

  • 符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里
  • 更好更方便的写法
  • 更加底层,提供的API丰富(request, response)
  • 脱离了XHR,是ES规范里新的实现方式
  • fetchtch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理
  • fetch默认不会带cookie,需要添加配置项
  • fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了量的浪费
  • fetch没有办法原生监测请求的进度,而XHR可以

为什么要用axios

  • axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征
    • 从浏览器中创建 XMLHttpRequest
    • 从 node.js 发出 http 请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求和响应数据
    • 取消请求
    • 自动转换JSON数据
    • 客户端支持防止CSRF/XSRF

ajax、axios、fetch 之间的详细区别以及优缺点

ajax、axios、fetch 之间的详细区别以及优缺点

将 jQuery 的 ajax、axios 和 fetch 做个简单的比较,所谓仁者见仁智者见智,最终使用哪个还是自行斟酌

1.jQuery ajax 

$.ajax({
type: ''POST'',
url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}
});
优缺点:

本身是针对 MVC 的编程,不符合现在前端 MVVM 的浪潮
基于原生的 XHR 开发,XHR 本身的架构不清晰,已经有了 fetch 的替代方案
JQuery 整个项目太大,单纯使用 ajax 却要引入整个 JQuery 非常的不合理(采取个性化打包的方案又不能享受 CDN 服务)
2.axios

axios({
method: ''post'',
url: ''/user/12345'',
data: {
firstName: ''Fred'',
lastName: ''Flintstone''
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
优缺点:

从 node.js 创建 http 请求
支持 Promise API
客户端支持防止 CSRF
提供了一些并发请求的接口(重要,方便了很多的操作)
3.fetch

try {
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}
优缺点:

符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里
更好更方便的写法
更加底层,提供的 API 丰富(request, response)
脱离了 XHR,是 ES 规范里新的实现方式
1)fetchtch 只对网络请求报错,对 400,500 都当做成功的请求,需要封装去处理
2)fetch 默认不会带 cookie,需要添加配置项
3)fetch 不支持 abort,不支持超时控制,使用 setTimeout 及 Promise.reject 的实现的超时控制并不能阻止请求过程继续在后台运行,造成了量的浪费
4)fetch 没有办法原生监测请求的进度,而 XHR 可以
为什么要用 axios?
axios 是一个基于 Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

从浏览器中创建 XMLHttpRequest
从 node.js 发出 http 请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
取消请求
自动转换 JSON 数据
客户端支持防止 CSRF/XSRF
---------------------
作者:WebCandy
来源:CSDN
原文:https://blog.csdn.net/twodogya/article/details/80223508
版权声明:本文为博主原创文章,转载请附上博文链接!

ajax、axios、fetch之间的优缺点对比

ajax、axios、fetch之间的优缺点对比

1.Ajax

_Ajax_即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。

用法:

$.ajax({
  type: ''POST'',
  url: url,
  data: data,
  dataType: dataType,
  success: function() {},
  error: function() {}
});

优点:

  • 提高了性能和速度减少了客户端和服务器之间的流量传输,同时减少了双方响应的时间,响应更快,因此提高了性能和速度
  • 交互性好:使用ajax,可以开发更快,更具交互性的Web应用程序
  • 异步调用:Ajax对Web服务器进行异步调用。这意味着客户端浏览器在开始渲染之前避免等待所有数据到达
  • 节省带宽:基于Ajax的应用程序使用较少的服务器带宽,因为无需重新加载完整的页面
  • 底层使用XMLHttpRequest

image.png

  • 拥有开源JavaScript库 : JQuery,Prototype,Scriptaculous等。
  • AJAX通过HTTP协议进行通信。

缺点:

  • 增加了设计和开发的时间
  • 比构建经典Web应用程序更复杂
  • Ajax应用程序中的安全性较低(容易收到CSRF和XSS攻击),因为所有文件都是在客户端下载的
  • 可能出现网络延迟的问题
  • 禁用javascript的浏览器无法使用该应用程序
  • 由于安全限制,只能使用它来访问服务于初始页面的主机的信息。如果需要显示来自其他服务器的信息,则无法在AJAX中显示。

2.axios

axios 基于promise用于浏览器和node.js的http客户端

用法:

axios({
    method: ''post'',
    url: ''/user/12345'',
    data: {
        firstName: ''Fred'',
        lastName: ''Flintstone''
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

优点:

  • 从node.js创建http请求
  • 在浏览器中创建XMLHttpRequest
  • 支持Promise API
  • 提供了一些并发请求的接口
  • 支持拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御CSRF/XSRF

3.fetch

fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。(然而问题还是有很多)

用法:

try {
  let response = await fetch(url);
  let data = response.json();
  console.log(data);
} catch(e) {
  console.log("Oops, error", e);
}

优点:

  • 符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象中
  • 更好更方便的写法
  • 更加底层,提供的API丰富(request,response)
  • 脱离了XHR,是ES规范里新的实现方式

缺点:

  • fetch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理
  • fetch默认不会带cookie,需要添加配置项
  • fetch不支持abort,不支持超时控制,使用setTimeoutPromise.rejectPromise.race结合setTimeout实现的超时控制并不能阻止请求过程继续在后台执行,造成了量的浪费
  • fetch没有办法原生监测请求的进度,而XHR可以

我们今天的关于vue之Promise、Fetch、Axios入门以及学习总结,涉及Express搭建接口vue promise axios的分享就到这里,谢谢您的阅读,如果想了解更多关于11-利用Promise的图片异步加载 / Promise封装ajax,模拟axios / Promise的finally原理、ajax、axios、fetch、ajax、axios、fetch 之间的详细区别以及优缺点、ajax、axios、fetch之间的优缺点对比的相关信息,可以在本站进行搜索。

本文标签: