• vue + axios---封装一个http请求


    在使用vue开发时,官方推荐使用axios来请求接口

    
    //    axios官方地址
    https://github.com/axios/axios
    

    但是axios并不像 vue-resource 一样拥有install,即不能直接 Vue.use(axios) 来使用,所以需要我们自己根据axios来写一个具有install方法的Http库。

    1.安装axios

    
    npm install axios
    

    2.创建Http.js文件

    
    import axios from 'axios'
    
    export default {
        install (Vue) {
        //    install方法,向Vue实例中添加一个$http方法
            Vue.prototype.$http = axios
            Vue.$http = axios
        },
        $http: axios
    }
    
    export const Http = axios
    
    

    3.引用

    
    import Vue from 'vue'
    import Http from './Http'
    
    Vue.use(http)
    

    如此,就可以在vue中直接使用axios了

    4.axios拦截器
    在开发过程中,会需要设置一些请求头,公共参数等,或者需要对请求结果进行统一处理(例如错误处理),这时候就可以用到axios拦截器

    创建interceptor.js文件

    
    import axios from 'axios'
    
    let interceptor = ''
    export const myInterceptor = interceptor
    
    //    设置请求拦截器
    export const setInterceptor = function (response) {
        axios.interceptors.request.use((config) => {
            config.headers.Authorization = token    //设置请求头Authorization
            config.headers.Accept = 'application/json'    //设置请求头Accept 
           /*
               具体配置需要根据实际开发情况来配置
           */
            return config
        })
    }
    //    移除请求拦截器
    export const clearInterceptor = function () {
      axios.interceptors.request.eject(myInterceptor)
    }
    
    

    ps:上例只示范了axios的请求拦截,回复拦截时同样的处理方式
    ps:在interceptor中暴露myInterceptor、setInterceptor与clearInterceptor 的原因是方便随时取消与设置

    5.设置axios默认请求地址

    
    axios.defaults.baseURL = 'http://172.0.0.1'
    

    虽说几乎都是使用webpack代理的方式来配置请求地址,但此方式依然有时会用到

    原文地址:https://segmentfault.com/a/1190000017352304

  • 相关阅读:
    怎么让图片居中显示?
    上传代码出现弹出框“请确保已在git中配置您的user.name和user.email”解决方法
    window.open()下载文件: 在当前页面打开方法
    修改网站颜色为黑白 (100% 灰度)/全页置灰
    ZMQ简单使用
    CCXT
    Python描述符详解
    自定义序列的修改、散列和切片
    使用__slots__类属性节省空间
    QGraphicsView实现虚拟摇杆
  • 原文地址:https://www.cnblogs.com/lalalagq/p/10114421.html
Copyright © 2020-2023  润新知