Vue3.0+Vite+Ts项目,集成 Axios

文章的配置,基于前面的项目配置,不知道的胖友可以先行了解一下

Vue3.0 + Vite + Ts项目配置

Axios 是一个流行的基于 Promise 的 HTTP 请求库,用于在浏览器和 Node.js 中进行 HTTP 请求。它提供了简单易用的 API,可以发送各种类型的请求(如 GET、POST、PUT、DELETE等),并处理响应数据,Axios 在前端工程化项目中有 99% 的概率会被优先选择。

下面,我们就来详细了解一下,项目中如何使用Axios以及它的相关配置!

文末附源码获取地址!文末附源码获取地址!文末附源码获取地址!

一、安装依赖

npm install axios

二、配置Axios

2.1. 目录结构

2.2 config.ts

这个文件主要用来定义请求头,如:后端请求链接,接口请求超时时间等基础配置信息

type AxiosHeaders =
  | 'application/json'
  | 'application/x-www-form-urlencoded'
  | 'multipart/form-data'

const config: {
  base_url: string
  result_code: number | string
  default_headers: AxiosHeaders
  request_timeout: number
} = {
  /**
   * api请求基础路径
   */
  base_url: import.meta.env.VITE_BASE_URL,
  /**
   * 接口成功返回状态码
   */
  result_code: 200,

  /**
   * 接口请求超时时间
   */
  request_timeout: 30000,

  /**
   * 默认接口请求类型
   * 可选值:application/x-www-form-urlencoded multipart/form-data
   */
  default_headers: 'application/json'
}

export { config }

2.3 service.ts

这里定义请求拦截器、响应拦截器之类

请求拦截器:将Token放入请求头,方便后端验证请求有效性

响应拦截器:处理后端返回的数据,针对不同的响应状态,给出用户友好的体验

import axios from 'axios';
import { config } from '@/config/axios/config'


const { base_url } = config

// 创建 axios 实例
const service = axios.create({
  baseURL: base_url,
  timeout: 5000
})

// 请求拦截器(添加 token)
service.interceptors.request.use(config => {
  // const token = localStorage.getItem('token')
  // if (token) {
  //   config.headers['Authorization'] = `Bearer ${token}`
  // }
  return config
})

//响应拦截器
service.interceptors.response.use((res) => {
    console.log('响应拦截器已启用', res)
    // 这里直接返回data,不要返回整个响应
    return res.data
}), (err: any) => {
    console.log('响应拦截器错误', err)
    return Promise.reject(err)
}


export { service }

2.4 index.ts

axios的总入口,这里定义基础的put、delete、get等请求返回,并将封装的axios返回

import { service } from './service'

import { config } from './config'

const { default_headers } = config


const request = (option: any) => {
  const { headersType, headers, ...otherOption } = option
  return service({
    ...otherOption,
    headers: {
      'Content-Type': headersType || default_headers,
      ...headers
    }
  })
}


export default {
  get: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', ...option })
    return res.data as unknown as T
  },
  post: async <T = any>(option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res.data as unknown as T
  },
  postOriginal: async (option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res
  },
  delete: async <T = any>(option: any) => {
    const res = await request({ method: 'DELETE', ...option })
    return res.data as unknown as T
  },
  put: async <T = any>(option: any) => {
    const res = await request({ method: 'PUT', ...option })
    return res.data as unknown as T
  },
  download: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', responseType: 'blob', ...option })
    return res as unknown as Promise<T>
  },
  upload: async <T = any>(option: any) => {
    option.headersType = 'multipart/form-data'
    const res = await request({ method: 'POST', ...option })
    return res as unknown as Promise<T>
  }
}

三、测试配置

创建一个api文件夹,用来与后端做交互

index.ts

import request from '@/config/axios'

export const test = () => {
    console.log(import.meta.env.VITE_API_BASE_URL);
    console.log("test");

    return request.get("/system/user/test");
}

在HelloWorld.vue中调用一下:

<script setup lang="ts">
import { ref } from 'vue'

import * as Api from '@/api'

defineProps<{ msg: string }>()

const count = ref(0)

const test = () => {
  // console.log(import.meta.env.VITE_API_BASE_URL);
  const data = Api.test();
  console.log("HelloWorld.vue:" + data);
}

</script>

<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <button type="button" @click="test">count is {{ count }}</button>
    <p>
      Edit
      <code>components/HelloWorld.vue</code> to test HMR
    </p>
  </div>

  <p>
    Check out
    <a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
      >create-vue</a
    >, the official Vue + Vite starter
  </p>
  <p>
    Learn more about IDE Support for Vue in the
    <a
      href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
      target="_blank"
      >Vue Docs Scaling up Guide</a
    >.
  </p>
  <p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

查看浏览器输出:

输出打印正确,说明我们的配置没有问题。

我是写代码的小和尚,平时喜欢写写博客,如果我的文章对您有所帮助,麻烦点赞收藏一下吧!让更多的人看见,谢谢大家!  

源码获取地址:https://pan.quark.cn/s/89843c24b2f9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值