【工作笔记0023】Vue 中使用 axios 对 http 请求进行封装

5 篇文章 0 订阅
1 篇文章 0 订阅

将以下代码放入 vue 项目结构中的 utils 文件夹 http.js 文件中:

'use strict'

import axios from 'axios'
import qs from 'qs'
//import storage from '@/utils/storage'

axios.defaults.withCredentials = true; //允许携带cookie

//请求拦截器:http请求发出前执行
axios.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  config.headers['Access-Control-Allow-Origin'] = '*';
  //config.headers['UserToken'] = storage.get('token');//这里token用于权限验证
  config.url = 'http://localhost:7777/api' + config.url;
  //config.url = '/api' + config.url;//项目发布的时候,使用这个,将前端项目和后端api项目放于同一个站点,即可避免跨域问题
  config.timeout = 50000;
  return config;
}, error => {
  return Promise.reject(error);
});

//响应拦截器:http请求返回后执行,根据实际情况是否使用
// axios.interceptors.response.use(response => {
//   if (!response || response.status != 200) {
//     //这里返回的数据结构可以根据实际情况自定义
//     return {
//       ExceptionCode: 0,
//       Code: 100000,
//       Message: '加载失败,请重试',
//       Data: null,
//       ServerTime: null
//     }
//   } else {
//     if (response.data.Code == 200) {
//       var t = typeof (response.data.Data);
//       //这里是为了防止服务器返回了一个json字符串,前端不能直接使用,所以处理转换为json对象
//       if (t == 'string' && response.data.Data.indexOf('{"') == 0) {
//         return {
//           ExceptionCode: response.data.ExceptionCode,
//           Code: response.data.Code,
//           Message: response.data.Message,
//           Data: JSON.parse(response.data.Data),
//           ServerTime: response.data.ServerTime
//         };
//       }
//       return response.data;
//     } else if (response.data.Code == 404) {
//       return {
//         ExceptionCode: 0,
//         Code: 404,
//         Message: '网络异常',
//         Data: null,
//         ServerTime: null
//       }
//     } else {
//       response.data.Message = !response.data.Message || response.data.Message == null || response.data.Message == '' ? '加载失败,请重试' : response.data.Message;
//       return response.data;
//     }
//   }
// }, error => {
//   return Promise.resolve(error.response);
// });

export default {
  post(url, data) {
    return axios({
      method: 'post',
      url: url,
      data: qs.stringify(data),
    }).then(
      (response) => {
        if (response.status && response.status != 200) {
          //这里返回的数据结构可以根据实际情况自定义
          return {
            ExceptionCode: 0,
            Code: 100000,
            Message: '加载失败,请重试',
            Data: null,
            ServerTime: null
          }
        }
        return response.data;
      }
    )
  },
  get(url, data) {
    return axios({
      method: 'get',
      url: url,
      params: data
    }).then(
      (response) => {
        if (response.status && response.status != 200) {
          return {
            ExceptionCode: 0,
            Code: 100000,
            Message: '加载失败,请重试',
            Data: null,
            ServerTime: null
          }
        }
        return response.data;
      }
    )
  }
}

用法如下:在需要使用http请求的组件中,先引入 http.js 文件,然后调用函数即可,示例:

<script>
import http from "@/utils/http";
import { async } from "q";

export default {
  data() {
    return {
      tableData: [], //列表数据
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    //获取列表数据
    getList: async function() {
        //这里需要使用 async  标记函数,使其支持异步,调用http请求数据时,使用 await 关键字等待数据返回
        var result = await http.get("/modelweek/list", {
            //这里写请求参数,传递一个对象即可    
        });
        if (result && result.length && result.length > 0) {
            this.tableData = result;
        }
    },
  }
};
</script>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值