首页 技术 正文
技术 2022年11月9日
0 收藏 546 点赞 3,000 浏览 1807 个字

一般我们写小型的项目是用不到封装axios实例

但是当我们写大型项目时  接口有时候多到有上百个接口,那我们在请求一次调用一次接口,接口上好多都是重复的,这个时候我们就可以封装axios实例,既节省了事件。有可以少些好多代码

首先我们要先安装axios

npm i axios –save

然后在vue项目中要创建两个文件夹api文件和http文件 当然文件名是自定义的

在http文件下http.js中要这样写

import axios from 'axios';//环境的切换 环境指的就是开发环境和生产环境
//开发环境(development) 中用到的是测试接口
if (process.env.NODE_ENV == 'development') {
axios.defaults.baseURL = 'http://120.53.31.103:84/'
}
//通过if判断处于开发环境还是生产环境
if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'https://www.365msmk.com/'
}//设置请求超时的事件
axios.defaults.timeout = 5000;
// 请求拦截
axios.interceptors.request.use(
config => {
//获取轮播图要设置的头信息
config.headers = { DeviceType: 'H5' }
//可每次发送请求之间的逻辑处理 ,比如判断token
return config
}
)
// 响应拦截
axios.interceptors.response.use(
response => {
//如果返回的·状态码为200时,说明接口请求成功
return response
},
error => {
if (error.response.status) {
}
}
)
//设置get请求方式 用promise方式返回的实例来实现
export function get(url, params) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
}//设置post请求方式 用promise方式返回的实例来实现
export function post(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}

  在api文件下api.js中要这样

首先要引入我们上个http.js文件中的两种请求方式post,get

import { post, get } from '../http/http.js'//首页讲师和精选课堂  资讯数据的请求
//Indexlist是我们定义的函数名 用于·在后面调用方法
export function Indexlist() {
// return get('这里面写的是请求接口后面需要拼接的一部分')
return get('api/app/recommend/appIndex')
}
//轮播图数据的请求
export function Indexbanner() {
return get('api/app/banner')
}

  

在vue组件中要这样应用


 1 import {Indexlist} from "../api/api.js";
2 //首先要引用api文件中当时定义的方法名 这样也用到了解构赋值 ,提取api.js文件中我们要用的数据
3
4 async mounted() {
5 //这里也可以用到async await语法
6 var ids = this.$route.query.item;
7 //接收上个页面传过来的id名
8 var objlist = await Indexlist({ id: ids });
9
10 console.log(objlist)
11 //打印我们请求那个接口,看下有数据没
12
13 this.CommentList = [...objlist.data.list];
14 //定义一个数组用扩展运算符进行赋值 console.log(this.CommentList);
15 }
16

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,490
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,905
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,738
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,491
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,129
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,292