Vue如何集成封装Axios


为了方便使用Ajax,Vue前端项目可以对Axios进一步封装,提高前端项目开发效率。

Axios安装

npm install axios@0.18.0

定义前端环境变量

封装Ajax请求,添加请求与响应拦截器

request.js

html 复制代码
import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
let apiBaseUrl = 'http://'+window.location.hostname + ":6060/";
if(process.env.USE_SAME_HOME=='true')
{
  if(process.env.USE_WEB_PORT != '')
    apiBaseUrl = 'http://'+window.location.hostname + ":"+process.env.USE_WEB_PORT+"/";
  else
    apiBaseUrl = 'http://'+window.location.hostname + "/";
}
else
{
  apiBaseUrl = process.env.SERVER_URL;
}

console.log("apiBaseUrl= ",apiBaseUrl)
// 创建 axios 实例
const service = axios.create({
  baseURL: apiBaseUrl, // api base_url
  timeout: 60000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    let data = error.response.data
    switch (error.response.status) {
      case 403:
        Message.error('拒绝访问')
        break
      case 500:
        Message.error('后台错误:'+error.response)
        break
      case 404:
          Message.error('很抱歉,资源未找到!')
        break
      case 504:
        Message.error('网络超时')
        break
      case 401:
        Message.error('未授权,请重新登录')
        break
      default:
        Message.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  if(config.method=='get'){
    //添加请求随机参数,避免Nginx配置缓存导致问题
    config.params = {
      _t: Date.parse(new Date())/1000,
      ...config.params
    }
  }
  return config
},(error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
    return response.data
  }, err)

export {
  service as axios
}

封装Http协议方法

http.js

html 复制代码
import Vue from 'vue'
import { axios } from '@/util/request'

export function postAction(url,parameter) {
  return axios({
    url: url,
    method:'post' ,
    data: parameter
  })
}

export function httpAction(url,parameter,method) {
  return axios({
    url: url,
    method:method ,
    data: parameter
  })
}

export function putAction(url,parameter) {
  return axios({
    url: url,
    method:'put',
    data: parameter
  })
}

export function getAction(url,parameter) {
  return axios({
    url: url,
    method: 'get',
    params: parameter
  })
}

export function deleteAction(url,parameter) {
  return axios({
    url: url,
    method: 'delete',
    params: parameter
  })
}

/**
export function downFile(url,parameter){
  return axios({
    url: url,
    params: parameter,
    method:'get' ,
    responseType: 'blob'
  })
}

export function downloadFile(url, fileName, parameter) {
  return downFile(url, parameter).then((data) => {
    if (!data || data.size === 0) {
      Vue.prototype['$message'].warning('文件下载失败')
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName)
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
    }
  })
}

export function uploadAction(url,parameter){
  return axios({
    url: url,
    data: parameter,
    method:'post' ,
    headers: {
      'Content-Type': 'multipart/form-data',  // 文件上传
    },
  })
}
*/

export function getFileAccessHttpUrl(avatar,subStr) {
  if(!subStr) subStr = 'http'
  try {
    if(avatar && avatar.startsWith(subStr)){
      return avatar;
    }else{
      if(avatar && avatar.length>0 && avatar.indexOf('[')==-1){
        return window._CONFIG['staticDomainURL'] + "/" + avatar;
      }
    }
  }catch(err){
   return;
  }
}

在组件中使用Axios的封装方法

SpringBoot后台项目添加跨域访问

java 复制代码
package com.hk.config;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CrosConfiguration extends WebMvcConfigurerAdapter {
    @Value("${cors.url}")
    private String corsUrl = null;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        System.out.println("corsUrl==="+corsUrl);
        String[] dimCors = corsUrl.split(",");
        registry
                .addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true)
                .allowedOrigins(dimCors)
                .maxAge(3600);
    }

}

测试

相关推荐
To_OC6 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮7 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny7 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹7 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny7 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC7 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn8 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
REDcker8 小时前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜8 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康9 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端