axios
pnpm i axios
封装axios.request方法
import axios,{type AxiosInstance,type AxiosRequestConfig} from 'axios';
class HttpRequest {
private defaults: AxiosRequestConfig;
private instance: AxiosInstance = {} as AxiosInstance;;
constructor(options:AxiosRequestConfig){
this.defaults = {
baseURL: ''
}
this.defaults = Object.assign(this.defaults, options);
}
interceptors(install:AxiosInstance){
install.interceptors.request.use(
config => {
let token = localStorage.getItem('token');
if (token) {
config.headers!.authorization = `token ${token}`;
}
return config;
},
err => {
return Promise.reject(err);
}
);
install.interceptors.response.use(
res => {
const { data, status } = res;
return data;
},
err => {
return Promise.reject(err);
}
);
}
request(options:AxiosRequestConfig){
options = Object.assign(this.defaults, options)
const instance = axios.create(options)
this.interceptors(this.instance);
return this.instance
}
}
const request = new HttpRequest({
baseURL: '/api'
});
export default request;
对请求进行封装
import http from '@/utils/http'
export const getUserInfo = () => {
return http.request({
url: '/getUserInfo',
method: 'get'
})
}
调用
import { getUserInfo } from '@/api/user'
import { defineStore } from 'pinia'
import {ref} from 'vue'
export const useUserStore = defineStore('user', ()=>{
const userInfo = getUserInfo()
})