• vue中请求接口


    request.ts

    1. import axios, {AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig} from 'axios';
    2. const env = import.meta.env
    3. const toLogin=()=>{
    4. window.location.href="/login"
    5. }
    6. const toError=()=>{
    7. window.location.href="/404"
    8. }
    9. let baseURL=""
    10. switch(env.MODE){
    11. case 'development':
    12. baseURL='/api';
    13. break;
    14. case 'test':
    15. baseURL='.........';
    16. break;
    17. case 'production':
    18. baseURL='.........';
    19. break;
    20. }
    21. const service:AxiosInstance = axios.create({
    22. timeout: 5000,
    23. baseURL
    24. });
    25. //请求拦截
    26. service.interceptors.request.use(
    27. (config: AxiosRequestConfig) => {
    28. if(!config.noToken){
    29. const token = localStorage.getItem('pc/GDToken');
    30. if(token){
    31. config.header.Authorization = token
    32. }
    33. }
    34. return config;
    35. },
    36. (error: AxiosError) => {
    37. console.log(error);
    38. return Promise.reject();
    39. }
    40. );
    41. //响应 拦截
    42. service.interceptors.response.use(
    43. (response: AxiosResponse) => {
    44. const { data } = reponse
    45. if (data.code === 0) {
    46. return Promise.resolve(data);
    47. } else {
    48. switch(data.code){
    49. case 401:
    50. console.log('401');
    51. toLogin();
    52. break;
    53. case 403:
    54. console.log('403');
    55. toLogin();
    56. break;
    57. default:
    58. console.log('403');
    59. }
    60. Promise.reject();
    61. }
    62. },
    63. (error: AxiosError) => {
    64. console.log(error);
    65. toError();
    66. return Promise.reject();
    67. }
    68. );
    69. export default service;

    api中新建的js文件

    1. import request from "@/utils/request";
    2. export const fetchData = () =>{
    3. return request({
    4. url:'.....',
    5. method:'get',
    6. })
    7. }
    8. export const fetchTest = (data) =>{
    9. return request({
    10. url:'.....',
    11. method:'get',
    12. params:data,
    13. })
    14. }
    15. export const changeTest = (data) =>{
    16. return request({
    17. url:'.....',
    18. method:'post',
    19. data:data,//放在data后就会包裹在Body内
    20. })
    21. }

    实际页面

    1. <template>
    2. </template>
    3. <script setup>
    4. import { onMounted } from "vue";
    5. import { fetchData, fetchTest, } from "@/api/test";
    6. const getList = async()=>{
    7. fetchData().then(res)=>{
    8. const { data } = res;
    9. ...
    10. }.catch((err)=>{})
    11. }
    12. onMounted(()=>{
    13. getList();
    14. })
    15. </script>

  • 相关阅读:
    【C语言】二分查找(含图解)
    【Docker】搭建MySQL主从复制,详细的图文展示
    leetcode 172-阶乘后的零
    【算法与数据结构】--高级算法和数据结构--哈希表和集合
    KubeSphere安装redis集群,全程超带劲
    125道Python面试题总结
    MySQL数据库基础
    MySQL高级语句
    计算机操作系统 第七章:文件管理(1)
    Java连接kubernates集群最优雅的两种方式
  • 原文地址:https://blog.csdn.net/qq_37815596/article/details/126677523