码迷,mamicode.com
首页 > 移动开发 > 详细

axios封装

时间:2020-11-02 10:48:44      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:odi   加载动画   idt   ons   --   ===   ssd   请求头   error   

封装axios.js

import axios from ‘axios‘

axios.defaults.widthCredentials = true;
axios.defaults.crossDomain = true;
axios.defaults.timeout = 1000;
axios.defaults.baseURL =‘url‘;
axios.defaults.headers.post[‘Content-Type‘] = ‘applicantion/json;charset=UTF-8‘;
axios.defaults.headers.get[‘Content-Type‘] = ‘application/json;charset=UTF-8‘;
axios.defaults.headers.common[‘Authorization‘] = ‘‘+Cookies.get(tokenKey); // 设置请求头为 Authorization
//加载动画显示
//创建axios实例
let util = {};
util.ajax = axios.create({});
//request 拦截器
util.ajax.interceptors.request.use( config =>{
    return config;
},error => {
    return Promise.reject(error);
})
// response 拦截器
util.ajax.interceptors.response.use( response =>{
    if(laoding){
        loading.close();
    }
    if(response.data.code === ‘401‘){
        console.log(‘response----------‘, response);
        //全局登陆过滤,当判读token失效或者没有登录时 返回登陆页面
        return false;
    }
    return Promise.resolve(response);
}, error =>{
    loading.close();
    return Promise.reject(error)
})
export default {
    /*
   * get方法,对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
   get (url, params) {
       return new Promise( (resolve, reject) =>{
           util.ajax.get(url, {params: params},
           {
                headers: {
                    ‘Authorization‘: ‘‘ + getToken(‘Token‘),
                    ‘token‘: getToken(‘Token‘)
                }
           }).then(res => {
               resolve(res)
           }).catch(err => {
               reject(err)
           })
       })
   },
    /**
   * post方法,对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
   post (url, params) {
    return new Promise((resolve, reject) => {
      util.ajax.post(url, params,
        {
          headers: {
            ‘Authorization‘: ‘‘ + getToken(‘Token‘),
          }
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}

引用axios.js,定义接口

import request from ‘@/api/axios‘

export function login (params) {
  return request.post(‘/user/login‘, params)
}
export function getUserAll (params) {
  return request.get(‘/user/getall‘, params)
}

页面使用方法

login(userinfo).then(res => {
    console.log(res)
    setToken(‘Token‘, res.token)
    this.$router.push({path: ‘/‘})
})

 

axios封装

标签:odi   加载动画   idt   ons   --   ===   ssd   请求头   error   

原文地址:https://www.cnblogs.com/llllpzyy/p/13912497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!