安装axios

npm i axios -D

封装axios

image.png

  1. src/api/home.js

    1. import index from './index'
  2. src/api/index.js ```javascript import {request} from ‘./request’

const index = { get(url, params) { const config = { method: ‘get’, url: url } if (params) { for (let key in params) { if (params[key].length === 0) { delete params[key] } } config.params = params } return request(config) }, getFile(url, params) { const config = { method: ‘get’, url: url, responseType: ‘blob’ } if (params) config.params = params return request(config) }, post(url, params) { const config = { method: ‘post’, url: url } if (params) config.data = params return request(config) }, put(url, params) { const config = { method: ‘put’, url: url } if (params) config.data = params return request(config) }, delete(url, params) { const config = { method: ‘delete’, url: url } if (params) config.params = params return request(config) } } export default index

  1. 3. src/api/request.js
  2. ```javascript
  3. import axios from 'axios'
  4. export function request(config) {
  5. // 创建axios的实例
  6. const instance = axios.create({
  7. baseURL: import.meta.env.VITE_APP_BASE_URL,
  8. timeout: 20000
  9. })
  10. // 请求拦截器配置
  11. instance.interceptors.request.use(config => {
  12. // config.headers.Authorization = window.sessionStorage.getItem('token')
  13. return config
  14. }, error => {
  15. console.log(error)
  16. return Promise.error(error)
  17. }
  18. )
  19. // 响应拦截器配置
  20. instance.interceptors.response.use(response => {
  21. return response.data
  22. }, error => {
  23. console.log(error)
  24. switch (error.response.status) {
  25. case 400:
  26. return Promise.reject(error.response.data)
  27. case 401:
  28. console.log("无权访问")
  29. break
  30. case 403:
  31. console.log("token过期啦")
  32. //window.location.href="/login"
  33. break
  34. case 404:
  35. console.log("404啦")
  36. break
  37. default:
  38. return Promise.reject(error)
  39. }
  40. return Promise.reject(error)
  41. })
  42. // 发送真正的网络请求
  43. return instance(config);
  44. }
  45. export default request

开发生产环境变量

项目开发过程中通常会有好几个环境,比如dev.test.development等模式,往往我们也需要在不同的环境下会有些值对应会变化,最常见的就是后台的接口api,开发环境的api和生产环境的api是不一致的,所以我们需要进行配置,在vite中我们需要进行这样的配置。参考文档:https://cn.vitejs.dev/guide/env-and-mode.html#env-files

  1. package.json指定mode ```javascript { “name”: “myblog_pc”, “version”: “0.0.0”, “scripts”: { “dev”: “vite —mode development”, “build”: “vite build —mode production”, “serve”: “vite preview” }, ………… }
  1. 2. 项目根目录创建.env.development文件
  2. ```javascript
  3. ENV= 'development'
  4. VITE_APP_TITLE = '测试环境'
  5. VITE_APP_BASE_URL = 'http://127.0.0.1:8000/'
  1. 项目根目录创建.env.production文件

    1. ENV= 'production'
    2. VITE_APP_TITLE = '生产环境'
    3. VITE_APP_BASE_URL = 'https://api.cuiliangblog.cn/'
  2. src/api/request.js使用环境变量

    1. // 创建axios的实例
    2. const instance = axios.create({
    3. baseURL: import.meta.env.VITE_APP_BASE_URL,
    4. timeout: 20000
    5. })