前言:vue的axios基于promise的http库,可以运行在浏览器和node环境中
一:api封装文件
request..js
import 'axios' from 'axios'//引用axios插件 npm install axios --s
//创建axios
const http= axios.create({
baseURL :process.env.VUE_APP_BASE_API,//url = base url + request url
timeout:15000//request timeout
})
//request interceptors //创建拦截器
http.interceptors.request.use(
config =>{
if(store.getters.token){
config.header['Authorization'] = getToken()
}
return config
}
error =>{
console.log(error)
return Promise.reject(error)
}
)
//拦截器响应拦截
http.interceptors.request.use(
response = >{
const res = response.data
if(res.code !== 200){
Message({
message:res.message||'Error',
type:'error',
duration:5*1000
})
return Promise.reject(new Error(res.message)||'Error')
}else{
return res
}
},
error = >{
Message({
message:error.message,
type:'error',
duration:5*1000
})
return Promise.reject(error)
}
}
)
export default http
二、api引用 src/api/datas.js
import http from '@/utils/http'
export function getData (data){
return http ({
url:'xxxxx',
method:'post',
data
})
}
三,.vue页面引用
import {getData} from '@/api/datas'
getData().then(res){
if(res.code == 200){this.$message.success('请求成功')}
}
纯手敲,应用需要修改,另一个大哥网址
https://blog.csdn.net/fzy_1939/article/details/125889440
标签:axios,http,vue,res,return,api,error,封装,message From: https://www.cnblogs.com/wdxue/p/16812875.html