先交代下基础版本:
“node”:“V16.14.1” “vue”: “^3.4.21” “vite”: “^5.2.0”
- 安装:npm install axios --save
- 在src目录下的utils文件夹创建一个request.js文件(示例代码,仅供参考):
//引入axios请求
import axios from 'axios'
// store
import useUserStore from '@/store/modules/userStore.js'
const store = useUserStore()
const BASE_API=import.meta.env.VITE_APP_BASE_API
// 创建axios实例
const service = axios.create({baseURL: BASE_API, //所有的后端接口请求地址前缀部分(没有后端请求不用写)timeout: 15000 // 请求超时时间,这里15秒//withCredentials: true,// 异步请求携带cookie,true为携带,false为不携带//请求头里面设置通用传参类型/*headers: {//设置后端需要的传参类型'Content-Type': 'application/json','token': 'x-auth-token',//一开始就要token'X-Requested-With': 'XMLHttpRequest',}*/
})// request拦截器
service.interceptors.request.use(config => {const value = JSON.parse(localStorage.getItem('token'));console.log(111, value.token)if (store.token) {config.headers['token'] = store.token // 让每个请求携带自定义token 请根据实际情况自行修改}return config
}, error => {console.log(error)return Promise.reject(error)
})// response拦截器
service.interceptors.response.use(response => {//对数据返回做什么const res = response.dataconst config = response.config// custom 表示自定义if (res.status_code !== 200 && !config.custom) {// if (res.status_code === 1002) {// loginOut()// } else if (loginVerify(res, config)) { // 登录功能验证// return res// } else {// Message({// message: res.status || 'Error',// type: 'error',// duration: 5 * 1000// })// }return Promise.reject(new Error(res.status || 'Error'))} else {if (response.headers['authorization'] || response.headers['Authorization']) {const _token = response.headers['authorization'] || response.headers['Authorization']store.dispatch('user/setToken', _token.split('Bearer ')[1])}return res}},error => {console.log('err' + error) // for debug// Message({// message: error.message,// type: 'error',// duration: 5 * 1000// })return Promise.reject(error)}
)
export default service
- 在src目录下创建一个api斜体样式文件夹,用来存放每个模块的接口请求,类如login.js
import request from '@/utils/request'//示例以application/json格式传参
export function login(data) {return request({url: '/admin/login',method: 'post',data: data})
}//示例在url后面拼接参数传参
export function test(params) {return request({url: '/admin/login',method: 'post',params: params})
}
- 使用,类如HelloWorld.vue:
<script setup>
import { login } from '@/api/login.js'
onMounted(() => {login({ phone: 18888888888 }).then(res => {console.log(res)}).catch(res => {console.log(res)})
})
</script>