Vue封装axios请求

1.引入axios

2.设置请求头

3.配置拦截器

4.引用

import axios from 'axios'
import {MessageBox} from 'element-ui'
import Vue from 'vue'
Vue.prototype.$axios = axios
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
const request = axios.create({
    timeout: 30000
});
request.interceptors.request.use(config => {
    return config
}, error => {
    Promise.reject
});

request.interceptors.response.use(
    response => response,
    error => {
        if (error.response && error.response.status) {
            const data = error.response.data || {};
            const key = data.errorKey || "";
            const title = data.title || "";
            const message = data.message || "";
            ResponseNotify(error, key, title, message, data)
        } else {
            MessageBox({
                type: 'error',
                title: '网络问题',
                message: '无法获得服务响应,可能是网络问题,请联系管理员。'
            })
        }
        return Promise.reject(error)
    });

export default request

注意:配置axios的默认URL(我的配置在配置文件中)

axios.defauls.baseURL = 'xxx'

在别的地方只需要  import引入文件就行

 Login(this.user).then(
             (response) => {
                if(response.data.success){
                      this.$store.commit('setUser', response.data.objects);
                      this.$parent.loginSuccess();
                 }else{
                     this.$message({
                          message:'登录失败:用户名或密码错误',
                          type:'error'
                          });
                       }
                    }
                );

 

 

你可能感兴趣的:(axios二次封装)