美文网首页
How to config axios in vue.js

How to config axios in vue.js

作者: ccphantom | 来源:发表于2017-07-23 10:39 被阅读0次

    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

          本文链接:https://www.haomeiwen.com/subject/henpkxtx.html