request.ts
- import axios, {AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig} from 'axios';
-
- const env = import.meta.env
-
- const toLogin=()=>{
- window.location.href="/login"
- }
-
- const toError=()=>{
- window.location.href="/404"
- }
-
- let baseURL=""
-
- switch(env.MODE){
- case 'development':
- baseURL='/api';
- break;
- case 'test':
- baseURL='.........';
- break;
- case 'production':
- baseURL='.........';
- break;
- }
- const service:AxiosInstance = axios.create({
- timeout: 5000,
- baseURL
- });
-
- //请求拦截
- service.interceptors.request.use(
- (config: AxiosRequestConfig) => {
- if(!config.noToken){
- const token = localStorage.getItem('pc/GDToken');
- if(token){
- config.header.Authorization = token
- }
- }
- return config;
- },
- (error: AxiosError) => {
- console.log(error);
- return Promise.reject();
- }
- );
-
- //响应 拦截
- service.interceptors.response.use(
- (response: AxiosResponse) => {
- const { data } = reponse
- if (data.code === 0) {
- return Promise.resolve(data);
- } else {
- switch(data.code){
- case 401:
- console.log('401');
- toLogin();
- break;
- case 403:
- console.log('403');
- toLogin();
- break;
- default:
- console.log('403');
- }
- Promise.reject();
- }
- },
- (error: AxiosError) => {
- console.log(error);
- toError();
- return Promise.reject();
- }
- );
-
- export default service;
api中新建的js文件
- import request from "@/utils/request";
-
- export const fetchData = () =>{
- return request({
- url:'.....',
- method:'get',
- })
- }
-
- export const fetchTest = (data) =>{
- return request({
- url:'.....',
- method:'get',
- params:data,
- })
- }
-
- export const changeTest = (data) =>{
- return request({
- url:'.....',
- method:'post',
- data:data,//放在data后就会包裹在Body内
- })
- }
实际页面
- <template>
- </template>
- <script setup>
- import { onMounted } from "vue";
- import { fetchData, fetchTest, } from "@/api/test";
- const getList = async()=>{
- fetchData().then(res)=>{
- const { data } = res;
- ...
- }.catch((err)=>{})
- }
- onMounted(()=>{
- getList();
- })
- </script>