How to config axios in vue.js

1. The configuration of axios in vue.js

import axios from 'axios'
import qs from 'qs'
import * as _ from '../util/tool'
axios.defaults.timeout = 5000;                        //response time
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';           // config request header
axios.defaults.baseURL = 'your interface address';   // config interface address
//POST method with inteceptor
axios.interceptors.request.use((config) => {
    // Do something before sending the request
    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
},(error) =>{
     _.toast("wrong params", 'fail');
    return Promise.reject(error);
});
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
    //对响应数据做些事
    if(!res.data.success){
        // _.toast(res.data.msg);
        return Promise.reject(res);
    }
    return res;
}, (error) => {
    _.toast("network er", 'fail');
    return Promise.reject(error);
});
//返回一个Promise(发送post请求)
export function fetch(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
               reject(error)
            })
    })
}

2. Use configed axios in vue.js

export default {
// User Login
    Login(params) {
        return fetch('/users/api/userLogin', params)
    },
  
// User register
    Register(params) {
        return fetch('/users/api/userRegist', params)
    },
// Send register verification code
    RegisterVerifiCode(tellphone) {
        return fetch('/users/api/registVerifiCode', {tellphone: tellphone})
    },
    ......
}

你可能感兴趣的:(How to config axios in vue.js)