如何用promise封装axios方法 |
您所在的位置:网站首页 › 用promise封装axios请求的好处 › 如何用promise封装axios方法 |
1.axios是什么? axios:易用、简洁且高效的http库;他基于promise。 2.axios特点? 支持promise:使用Promise管理异步,告别传统callback方式; 支持node端和浏览器端:同样的API,node和浏览器全支持,平台切换无压力; 丰富的配置项:支持拦截器等高级配置; 从浏览器中创建XMLHttpRequests; 3.实例? (1)执行get请求: // 为给定 ID 的 user 创建请求 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); });(2)执行post请求: axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });(3)执行多个并发请求: function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 }));上述案例来自axios中文文档:http://www.axios-js.com/zh-cn/docs/ 4.用promise封装axios? 在实际项目里为了更方便使用axios获取后台数据,在这里进行封装。ue项目里封装方法一般放在utils文件夹里,src下新建一个utils文件夹,index.js文件。 /* eslint-disable no-unused-vars */ import axios from 'axios'; // const get = () => { // console.log('get请求'); // } // const post = () => { // console.log('post请求') // } // export{ // get, // post // } // process.env.NODE_ENV环境 let baseURL; if(process.env.NODE_ENV=='development'){ baseURL = 'http://132.232.94.151:3000/api' }else{ baseURL = '/xxx' } // baseURL es6 方法 const $http = axios.create({ baseURL, }) // create 是axios自带的方法 export const get = (url,params)=>{ params = params || {}; return new Promise((resolve,reject)=>{ // axiso 自带 get 和 post 方法 $http.get(url,{ params, }).then(res=>{ if(res.data.status===0){ resolve(res.data); }else{ alert(res.data.msg) } }).catch(error=>{ alert('网络异常'); }) }) } export const post = (url,params)=>{ params = params || {}; return new Promise((resolve,reject)=>{ $http.post(url,params).then(res=>{ if(res.data.status===0){ resolve(res.data); }else{ alert(res.data.msg); } }).catch(error=>{ alert('网络异常'); }) }) }main.js文件中做如下配置: import { get, post } from "./utils/index"; Vue.prototype.$http = { get, post };(1)上述使用了构造函数的原型prototype(vue属于构造函数); (2)声明一个全局变量并且把封装好的get和post方法放在里面。 使用封装后的函数: created() { this.getFilmList(); }, methods: { async getFilmList() { const url = "/film/getList"; // 要访问第二页的话在网址后面加 ?type=2&pageNum=页数 const res = await this.$http.get(url); this.filmList = res.films; },注意:因为是promise封装的函数方法,所以使用的时候要加上async 函数(){ await 数据} 不然会报错,因为没有完成异步转同步。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |