Vue项目封装Axios[Vue.js项目实践: 新冠自检系统]

Logo

新冠疫情自我检测系统网页设计开发文档

Sylvan Ding 的第一个基于 Vue.js 的项目. 本项目所提供的信息,只供参考之用,不保证信息的准确性、有效性、及时性和完整性,更多内容请查看国家卫健委网站!
Explore the docs »

View Demo · Report Bug · Request Feature

homepage

Vue项目封装Axios

During the development process, Axios needs to be further encapsulated to facilitate its use in the project, which tends to reduce code duplication.

开发环境

node14.16.1
npm8.18.0
vue-cli2.9.6
vue2.5.2

解决方案

In order to avoid polluting the global Axios and affect other requests when one request modified, we use src/utils/requests.js to create a new instance of axios with a custom config. You can switch different base URLs according to different environments. And all JSON mocks used by Axios in development environment have been put in static/mock/*.json for the purpose of keeping web’s original file structure, which allows you to access them by http://localhost:8080/static/mock/*.json.

When using Axios to Get data and load it in Element UI components, we import request.js and create function loadData() in Vue methods, then call this method in the hook function mounted():

<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      tableData: [],
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    loadData() {
      request.get('/to/mock/file.json').then((response) => {
        this.tableData = response.data
      })
    },
  },
}
</script>

src/utils/requests.js:

import { errorMsg } from '@/utils/msgsettings.js'
const axios = require('axios')
const qs = require('qs')

const prodBaseURL = 'http://localhost:5000'

let axiosConfig = {
  timeout: 3000,
  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [
    function(data, headers) {
      // Do whatever you want to transform the data
      headers['content-type'] = 'application/x-www-form-urlencoded'
      data = qs.stringify(data)
      return data
    },
  ],
}

// set baseURL under production environment
if (process.env.NODE_ENV === 'production') {
  axiosConfig.baseURL = prodBaseURL
}

const instance = axios.create(axiosConfig)

// Add a request interceptor
instance.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config
  },
  function(error) {
    // Do something with request error
    errorMsg(error)
    return Promise.reject(error)
  }
)

// Add a response interceptor
instance.interceptors.response.use(
  function(response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log(response)
    return response
  },
  function(error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    errorMsg(error)
    console.log(error)
    return Promise.reject(error)
  }
)

export default instance

转载请注明出处:©️ Sylvan Ding 2022

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值