axios
-
promise
-
封装
在实际项目里为了更方便的使用axios获取后台数据,这里我们用promise封装一下
vue项目里封装方法我们一般放在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://192.168.3.40/xxx'}else{baseURL = 'http://47.114.48.244/xxx'}或者简写:baseURL = process.env.VUE_APP_BASE_API;// 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.code===0){resolve(res.data);}else{alert(res.data.msg)}}).catch(error=>{// 这里也需要捕获异常 例如: 通过请求获取的数据res.data需要JSON.parse解析 如果解析报错错误 则只能在.catch中捕获 而在try/catch中无法捕获 或者 请求响应过程产生的报错 在 .catch 中捕获console.log(error);})})}export const post = (url,params)=>{params = params || {};return new Promise((resolve,reject)=>{$http.post(url,params).then(res=>{if(res.data.code===0){resolve(res.data);}else{alert(res.data.msg);}}).catch(error=>{console.log(error);})})}
这里用到了的知识点
1.baseURL
2.axios的create方法
3.promise以及axios的get和post
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() {// 完美写法: utils内封装的方法要写.catch来捕获请求相应过程中产生的异常错误 并且 还需要通过async/await的try/catch捕获try里面代码的异常错误 例如: 调用的this.$http.get方法不存在 或者 这里得到的数据res需要JSON.parse()而产生报错 都在catch中捕获try{const url = "/film/getList";// 要访问第二页的话在网址后面加 ?type=2&pageNum=页数const res = await this.$http.get(url);this.filmList = res.films;} catch(error) {console.log(error);}},
这里注意的是,因为是promise封装的函数方法,所以使用的时候要加上
async 函数(){ await 数据} 不然会报错,因为没有完成异步转同步
axios
