vue3+vite package configuration axios

configure axios

1. Installation

yarn add axios 

2. Create a new utils/axios.ts

import axios from 'axios';

/*
 * 创建实例
 * 与后端服务通信
 */
const HttpClient = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
});

/**
 * 请求拦截器
 * 功能:配置请求头
 */
HttpClient.interceptors.request.use(
  (config) => {
    const token = '222';
    config.headers.authorization = 'Bearer ' + token;
    return config;
  },
  (error) => {
    console.error('网络错误,请稍后重试');
    return Promise.reject(error);
  },
);

/**
 * 响应拦截器
 * 功能:处理异常
 */
HttpClient.interceptors.response.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default HttpClient;

3. Create a new apis/model/userModel.ts

Define request parameter types and return data types

//定义请求参数
export interface ListParams {
  id: number; //用户id
}

export interface RowItem {
  id: number; //文件id
  fileName: string; //文件名
}

//定义接口返回数据
export interface ListModel {
  code: number;
  data: RowItem[];
}

4. Create a new apis/user.ts

import HttpClient from '../utils/axios';
import type { ListParams, ListModel } from './model/userModel';

export const getList = (params: ListParams) => {
  return HttpClient.get<ListModel>('/list', { params });
};

5. use

<script setup lang="ts">
import { getList } from '@/apis/user';

getList({ id: 2 });
</script>

In the chrome network, you can see the request http://127.0.0.1:9000/api/list?id=2


to use yarn to install and uninstall packages - Programmer Sought

Guess you like

Origin blog.csdn.net/qq_44848480/article/details/131434339