vue-axios

axios请求问题

问题:axios请求发送请求后先执行下面内容,然后执行完毕后再加载then的内容

使用:我们在当前页面使用axios发送请求,如果在其他页面我们需要解决:

  1. js需要解决异步问题
  2. js需要解决拦截问题
  3. then直接返回了Promise ,then下面执行不在返回

查看原因:

  1. 我们先在js中做发有一个get请求:
const queryComponent = 'Componentlibrary/queryComponent' // 初始化
export default {

    /**
       * @description get请求
       * @param str
       * @returns {string}
       * @constructor herry
       * @Instructions 
       */
    getQueryComponent: function () {
        // 请求方法
        return axios.get(queryComponent).then(res => {

            console.log("我执行了返回结果", res.data.data);
        });
    },
}
  1. 我们在vue文件中接收一下:
import library from "../../../api/Super/library/library";

getQueryComponent_test() {
      this.classList = [];
      // library.getQueryComponent()
      const a = library.getQueryComponent();

      console.log(a);
    },

vue-axios_第1张图片

axios使用

  1. main.js中全局引用axios
import axios from "../src/utils/dynamicAxios";  // 引入拦截器文件,下面有代码
Vue.prototype.$axios = axios; // 全局挂载axios

//引入提示框:
import ElementUI from 'element-ui';  //引入emement组件库
import 'element-ui/lib/theme-chalk/index.css';  // 引入element样式
import { Message } from 'element-ui';
Vue.prototype.$message = Message; // 顶部提示设置位vue方法

// 引入返回code码:
import { responseCode } from "../src/utils/responseCode"; // 引入后端返回code码
Vue.prototype.$responseCode = responseCode; // 全局挂载返回的code码
  1. code码js

const responseCode = {
    SUCCESSCODE: '0000',
    FAILCODE: '1111',
    NULLCODE: '2222'
}

export {
    responseCode
}
  1. 当前页面写拦截请求
	// 3.1使用get请求: queryComponent为地址

 getQueryComponent() {
      // 请求方法
      this.$axios.get(queryComponent).then(res => {
        switch (res.data.code) {
          case this.$responseCode.SUCCESSCODE:
            console.log(res.data.data);

            break;
          case this.$responseCode.NULLCODE:
            this.$message({
              message: this.messageInfo.message.noData,
              center: this.messageInfo.center.centerTrue, //居中显示
              type: this.messageInfo.type.warning,
              showClose: this.messageInfo.showClose.showCloseTrue, //是否显示关闭按钮
              offset: this.messageInfo.offset.offset, //提示框距离顶部距离
              duration: this.messageInfo.duration.duration
            });
            break;
          default:
            this.$message({
              message: this.messageInfo.message.loadFailed,
              center: this.messageInfo.center.centerTrue, //居中显示
              type: this.messageInfo.type.warning,
              showClose: this.messageInfo.showClose.showCloseTrue, //是否显示关闭按钮
              offset: this.messageInfo.offset.offset, //提示框距离顶部距离
              duration: this.messageInfo.duration.duration
            });
            break;
        }
      });
    },
	// 3.2使用post请求:updateComponent为地址,modelData为model体数据
  postUpdateComponent() {
      var modelData = [];
      this.changeLocation();
      for (let i = 0; i < this.classList.length; i++) {
        modelData.push({
          groupId: this.classList[i].groupId,
          groupName: this.classList[i].title,
          isUsable: this.classList[i].isUsable,
          groupSequence: this.classList[i].position,
          componentId: this.classList[i].componentId
        });
      }
      this.$axios.post(updateComponent, modelData).then(res => {
        switch (res.data.code) {
          case this.$responseCode.SUCCESSCODE:
           console.log("成功")
            break;
          default:
            this.$message({
              message: this.messageInfo.message.saveFailed,
              center: this.messageInfo.center.centerTrue, //居中显示
              type: this.messageInfo.type.success,
              showClose: this.messageInfo.showClose.showCloseTrue, //是否显示关闭按钮
              offset: this.messageInfo.offset.offset, //提示框距离顶部距离
              duration: this.messageInfo.duration.duration
            });
            break;
        }
      });
    },

axios拦截请求

  1. 我们需要设置三个开发文件,脚手架为4.0

    vue-axios_第2张图片
    每个文件名字相同,但是地址不同分别为:prod/test/dev


	//本地后端地址
	VUE_APP_BACKEND_URL=http://192.168.0.1:8091/ddd-web/
	
	// 打包文件名字
	outputDir="ddd_dev"
  1. 配置拦截请求如下:
import axios from 'axios'// 引用官方的axios库,用于我们创建自己封装的axios
import store from '../store'
import { Notify } from 'vant' //引用vant组件中的Toast 用于弹出提示框
import router from '../router' //引用router,用于在某些错误情况下跳转路由

//设置axios的基础url,用于标识项目的地址
// axios.defaults.baseURL = 'http://192.168.22.126:8118/integral-web'

axios.defaults.baseURL = process.env.VUE_APP_BACKEND_URL

/*
 * request的请求拦截器:请求前的操作
 */
axios.interceptors.request.use(config => {
  store.state.isShowLoading = true // 加载中动画显示
  store.state.isShowLoadFailed=false  //加载失败页面关闭

  // config.headers.Authorization = store.state.token
  //localStorage.getItem("token")//store.getToken()

  return config
}, error => { Promise.reject(error) })

/**
  * response接收拦截器:接收后的操作
  */
// 
axios.interceptors.response.use(response => {

  store.state.isShowLoading = false // 加载中动画关闭

  //此处表示我们的请求让服务器正确的接收了,并且返回了数据(状态码 200)
  // 
  return response
}, error => {
  //此处表示服务器没有正确的处理我们的请求,然后给我们返回了错误的数据信息
  //status 表示 错误的http状态码
  if (!error.response) {
    // Notify({ type: 'warning', duration: 1000, message: '服务器出现问题,请稍后重试!' });
    // router.push({ name: 'login' });
    store.state.isShowLoadFailed=true  //加载失败页面显示
    store.state.isShowLoading = false // 加载中动画关闭
  }
  const status = error.response.status
  switch (status) { // 其他情况补充处理
    case 500:
      Notify({ type: 'warning', duration: 1000, message: '服务器响应出现问题,请稍后重试!' });
      break;
    case 400:
      Notify({ type: 'warning', duration: 1000, message: '服务器无法理解请求参数,请稍后重试!' });
      break;
    case 401:
      Notify({ type: 'warning', duration: 1000, message: '访问资源未授权,请登陆后重试!' });
      router.push({ name: 'login' });
      break;
    case 403:
      Notify({ type: 'warning', duration: 1000, message: '请求资源暂时不可用,请登陆后重试!' });
      router.push({ name: 'login' });
      break;
    case 404:
      Notify({ type: 'warning', duration: 1000, message: '请求资源暂不存在,请稍后重试!' });
      break;
  }
  return Promise.reject(error)
}
)
export default axios

你可能感兴趣的:(#,Vue)