1. Install axios
1 |
npm install axios --save |
2. Configure axios and add interceptors
Create a new request folder in the src directory, create a new index.ts (or .js) file in it, and edit the code as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import axios from 'axios' // 创建一个 axios 实例 const service = axios.create({
baseURL: '/api' , // 所有的请求地址前缀部分 timeout: 60000, // 请求超时时间毫秒 withCredentials: true , // 异步请求携带cookie headers: {
// 设置后端需要的传参类型 'Content-Type' : 'application/json' , 'token' : 'your token' , 'X-Requested-With' : 'XMLHttpRequest' , }, }) // 添加请求拦截器 service.interceptors.request.use( function (config) {
// 在发送请求之前做些什么 return config }, function (error) {
// 对请求错误做些什么 console.log(error) return Promise.reject(error) } ) // 添加响应拦截器 service.interceptors.response.use( function (response) {
console.log(response) // 对响应数据做点什么 // dataAxios 是 axios 返回数据中的 data const dataAxios = response.data // 这个状态码是和后端约定的 const code = dataAxios.reset return dataAxios }, function (error) {
// 对响应错误做点什么 console.log(error) return Promise.reject(error) } ) export default service |
3. Use axios to send requests
Create a new apis folder in the src directory, and put all future request files in it, for example, create a new interface user.ts to request user information, the code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// 导入axios实例 import httpRequest from '@/request/index' // 定义接口的传参 interface UserInfoParam {
userID: string, userName: string } // 获取用户信息 export function apiGetUserInfo(param: UserInfoParam) {
return httpRequest({
url: 'your api url' , method: 'post' , data: param, }) } |
Then use this request in a specific business page, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script setup lang= "ts" > import { onMounted } from 'vue' import { apiGetUserInfo } from '@/apis/user' function getUserInfo() {
const param = {
userID: '111' , userName: '2222' , } apiGetUserInfo(param).then((res) => {
console.log(res) }) } onMounted(() => {
getUserInfo() }) </script> |
Attachment: Global introduction of axios in Vue3
main.js
1 2 3 |
import axios from 'axios' const app = createApp(App) // 将默认改写为这样 app.provide( '$axios' , axios) |
Use axios (compositionAPI) in the component
1 2 3 4 5 6 7 8 9 |
<script setup> import { inject } from 'vue' const $axios = inject( '$axios' ) $axios.get( 'https://api.com' ).then((resp) => { console.log(resp.data) }). catch ((err) => {
console.log(err) }) </script> |