Api请求

9/7/2021

# 读取数据

import { emailApi } from '@/api/email.js'
export default {
  data () {
    returen {
      searchForm: {
        pageNum: 1,
	pageSize: 10
      }
    }
  },
  mounted () {
    this.load()
  },
  methods: {
    // 异步加载数据
    async load () {
      let res = await emailApi.emailPageQuery(this.searchForm)
      let datas = res.data
      console.log(datas)
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# API封装

import { postAxios, getAxios } from './method'
export const emailApi = {
  // 分页查询邮件
  emailPageQuery: data => {
    return postAxios('/email/page/query', data)
  },
  // 删除邮件
  emailDelete: id => {
    return getAxios('/email/delete/' + id)
  }
}

1
2
3
4
5
6
7
8
9
10
11
12

# http.js

import Axios from 'axios';
import config from '@/config';
import { Message, Spin } from 'iview';
import Cookies from 'js-cookie';
import { TOKEN_KEY } from '@/lib/cookie';
// 之所以封装这个axios,是因为在一些请求中,无法上传信息,很尴尬,估计原因是继承的有问题,无法携带headers
export const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro;
export const socketBaseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.socketDev : config.baseUrl.socketPro;

let axios = Axios.create({
  baseURL: baseUrl,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
});
// 添加请求拦截器

axios
  .interceptors
  .request
  .use(function (config) {
    // 在发送请求之前做些什么
    config.headers['x-access-token'] = Cookies.get(TOKEN_KEY);
    return config;
  }, function (error) {
    // 对请求错误做些什么
    Spin.hide();
    return Promise.reject(error);
  });
// 添加响应拦截器
axios
  .interceptors
  .response
  .use((res) => {
    let { data } = res;
    if (data.code !== 1) {
      if (data.code === 1001) {
        Cookies.remove(TOKEN_KEY);
        localStorage.clear();
        window.location.href = window.location.pathname + '#/login';
        Message.error('未登录,或登录失效,请登录');
      } else if (data.code === 502) {
        window.location.href = window.location.pathname + '#/500';
      } else {
        Message.error(data.msg);
      }
      return Promise.reject(res);
    }
    return data;
  }, (error) => {
    Spin.hide();
    Message.error('服务内部错误');
    // 对响应错误做点什么
    return Promise.reject(error);
  });

export const postAxios = (url, data) => {
  return axios.post(url, data);
};
export const getAxios = (url, data) => {
  return axios.get(url, {
    params: data
  });
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

作者简介: 卓大 (opens new window), 1024创新实验室主任,混迹于各个技术圈,熟悉点java,略懂点前端。

加“卓大”微信,入群 关注 1024创新实验室! 我要请 1024创新实验室 喝胡辣汤~
告白气球 (钢琴版)
JESSE T