方式1: 将axios挂载到vue原型对象上
第一种:将接口封装成函数形式
1. 在main.js导入
import axios from 'axios'
导入封装 的api并注册
import api from './http/index'
Vue.use(api);
将axios挂载到原型对象上
Vue.prototype.$axios = axios
2.http/index.js文件中
// 倒入所有接口
import apiList from './interface'
const install = Vue => {
if (install.installed) { return }
install.installed = true
Object.defineProperties(Vue.prototype, {
// 注意哦,此处挂载在 Vue 原型的 $api 对象上
$api: {
get () {
return apiList
}
}
})
}
export default install
3.http/interface.js 接口文件
import axios from './api'
const api = {}
// 获取新闻列表
api.newsList = params => axios({
url: '/cms/post/lists',
method: 'get',
params
})
// 获取新闻详情
api.newsDetail = params => axios({
url: '/cms/post/info',
method: 'get',
params
})
// 获取产品列表
api.productsList = params => axios({
url: '/produce/index/lists',
method: 'get',
params
})
// 获取产品详情
api.productsDetail = params => axios({
url: '/produce/index/detail',
method: 'get',
params
})
// 获取职称列表
api.positionList = params => axios({
url: '/produce/job/lists',
method: 'get',
params
})
// 获取招聘列表
api.advertiseList = params => axios({
url: '/produce/offers/lists',
method: 'get',
params
})
// 获取招聘详情
api.advertiseDetail = params => axios({
url: '/produce/offers/detail',
method: 'get',
params
})
// 获取后台配置
api.address = params => axios({
url: '/core/index/config',
method: 'get',
params
})
// 获取首页
api.indexnews = params => axios({
url: '/produce/index/home',
method: 'get',
params
})
// 获取热门资讯
api.hotnews = params => axios({
url: '/cms/post/hots',
method: 'get',
params
})
// 留言反馈
api.feedback = data => axios({
url: '/core/message/add',
method: 'post',
data
})
// 获取相关产品
api.aboutproduct = params => axios({
url: '/produce/index/about',
method: 'get',
params
})
export default api
4.http/api.js
import axios from 'axios' // 注意先安装哦
import config from './config.js' // 倒入默认配置
import router from '../router/index'
// import vuex from '../store'
export default function $axios (options) {
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: config.baseURL,
async:false,
headers: config.headers,
transformResponse: [function (data) {
}]
}
)
// request 拦截器
instance.interceptors.request.use(
config => {
config.headers['Content-Type'] = 'application/json;charset=UTF-8'
console.log(123);
// Tip: 1
// 请求开始的时候可以结合 vuex 开启全屏的 loading 动画
// Tip: 2
// 带上 token , 可以结合 vuex 或者重 localStorage
// if (vuex.state.setting.schoolId!=''){
// config.headers['SCHOOL_ID']=vuex.state.setting.schoolId;
// }
if (localStorage.getItem('token')) {
config.headers['Authorization'] = `${localStorage.getItem('token')}`
}else{
console.log(localStorage.getItem('token'))
}
// // 重定向到登录页面
// }
// Tip: 3 dd
// 根据请求方法,序列化传来的参数,根据后端需求是否序列化
if (config.method.toLocaleLowerCase() === 'post' ||
config.method.toLocaleLowerCase() === 'put' ||
config.method.toLocaleLowerCase() === 'delete') {
config.data = config.data
}
return config
},
error => {
// 请求错误时做些事(接口错误、超时等)
// Tip: 4
// 关闭loadding
console.log('request:', error)
// 1.判断请求超时
if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
console.log('根据你设置的timeout/真的请求超时 判断请求现在超时了,你可以在这里加入超时的处理方案')
// return service.request(originalRequest);//例如再重复请求一次
}
// 2.需要重定向到错误页面
const errorInfo = error.response
console.log(errorInfo)
if (errorInfo) {
// error =errorInfo.data//页面那边catch的时候就能拿到详细的错误信息,看最下边的Promise.reject
const errorStatus = errorInfo.status // 404 403 500 ... 等
router.push({
path: `/error/${errorStatus}`
})
}
return Promise.reject(error) // 在调用的那边可以拿到(catch)你想返回的错误信息
}
)
// response 拦截器
instance.interceptors.response.use(
response => {
var dataStr
var dataObj
// IE9时response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串)
// console.log(response);
if (response.data === undefined) {
dataStr = response.request.responseText
} else {
dataStr = response.data
}
// 根据返回的code值来做不同的处理(和后端约定)
dataObj = JSON.parse(dataStr)
if (dataObj.code != 200) {
const err = new Error()
err.message = dataObj.msg
err.status = dataObj.result
throw err
}
return dataObj
},
err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = '请求错误'
break
case 401:
err.message = '未授权,请登录'
break
case 403:
err.message = '拒绝访问'
break
case 404:
err.message = `请求地址出错: ${err.response.config.url}`
break
case 408:
err.message = '请求超时'
break
case 500:
err.message = '服务器内部错误'
break
case 501:
err.message = '服务未实现'
break
case 502:
err.message = '网关错误'
break
case 503:
err.message = '服务不可用'
break
case 504:
err.message = '网关超时'
break
case 505:
err.message = 'HTTP版本不受支持'
break
case 401:
localStorage.removeItem('token')
router.push({
path: `/login`
})
err.message = '登录超时'
default:
}
}
// 此处我使用的是 element UI 的提示组件
return Promise.reject(err) // 返回接口返回的错误信息
}
)
// 请求处理
instance(options)
.then((res) => {
resolve(res)
return false
})
.catch((error) => {
reject(error)
})
})
}
5.http/config.js
export default {
method: 'post',
//baseURL: 'http://192.168.1.65:8080/pandora',http://hmapi.demo.lyunweb.com/
baseURL: 'http://hmapi.demo.lyunweb.com/index.php/api/v1',
// 请求头信息
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
// 参数
data: {},
// 设置超时时间
timeout: 5000,
// 携带凭证
withCredentials: false,
// 返回数据类型
responseType: 'json'
}
5.调用接口
5.1不带参数的
```css
hotNews() {
this.$api.hotnews({}).then((res) => {
this.dataList = res.data.dataList
console.log(res.data)
})
.catch((err) => {
console.log(err)
})
},
5.2 带参数的
```css
newsDetail() {
this.$api
.newsDetail({
id: this.newsid,
})
.then((res) => {
console.log(res.data)
this.newsinfo = res.data.info
})
.catch((err) => {
console.log(err)
})
},
第二种方式: 直接调用
1.在main.js中导入
// 导入axios
import axios from 'axios'
// 给Vue原型添加一个属性$http为axios对象
Vue.prototype.$http = axios
// 配置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1'
2.调接口
2.1get方式
sync getUserList () {
const { data: res } = await this.$http.get('users', {
params: this.queryInfo
})
// console.log(res);
if (res.meta.status !== 200) {
return this.$message.error(res.meta.msg)
}
this.userlist = res.data.users
this.total = res.data.total
},
2.1post方式
// 点击添加用户的确认按钮,添加用户
addUser () {
// 添加用户表单的预检验
this.$refs.addFormRef.validate(async (valid) => {
if (!valid) return
// 可以发起添加用户的网络请求
const { data: res } = await this.$http.post('users', this.addForm)
console.log(res)
if (res.meta.status !== 201) {
return this.$message.error('添加用户失败')
}
this.$message.success('添加用户成功!')
// 隐藏添加用户的对话框
this.dialogVisible = false
// 重新获取用户列表
this.getUserList()
})
},