zoukankan      html  css  js  c++  java
  • vue中采用axios发送请求及拦截器

      这几天在使用vue中axios发送get请求的时候很顺手,但是在发送post请求的时候老是在成功的回调函数里边返回参数不存在,当时就纳闷了,经过查阅资料,终于得到了解决方案,在此做一总结:

      首先我们在运用npm install axios的时候就会默认安装qs,因此我们就得将qs引入到axios中,然后需要再通过实例化一个新的axios,并且设置他的消息头为'content-type': ‘application/x-www-form-urlencoded'

     1 let qs = require('qs'); 
     2 let instance = axios.create({
     3      headers: { 'content-type': 'application/x-www-form-urlencoded' }
     4  });
     5 let data = qs.stringify({
     6      "user_id": this.user_id,
     7      "cate_name": this.cateName
     8    });
     9 instance.post("./frontend/web/cate/create", data)
    10     .then(res => {
    11        if (res.status == 200) {
    12          alert("添加成功!")
    13          this.initTableData();
    14        }
    15      })
    16      .catch(err => {
    17        console.log(err);
    18      });

    优化后:

    main.js:

    import QS from 'qs'
    Vue.prototype.qs = QS
    Vue.prototype.$$ajax = Axios.create({
      header: { "content-type": "application/x-www-form-urlencoded" }
    })

    ***.vue:

    let data = this.qs.stringify({
              id: this.user_id,
              password: this.newPassword
            });
            this.$$ajax.post("./frontend/web/user/uppwd", data)
              .then(res => {
                if (res.status == 200) {
                  alert("恭喜你,密码修改成功!");
                  this.$router.push({ name: "personalCenter" });
                }
              })
              .catch(err => {
                console.log(err);
              })

    这样就能解决vue中利用axios发送post请求失败的问题。

    另外,我们通常在利用 axios 的时候,需要对其进行拦截(请求数据出现 loading 图标),下面代码可对 axios 请求进行拦截:

    // http request 请求拦截器,有token值则配置上token值
    Axios.interceptors.request.use(
        config => {
            if (token) {  // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
                config.headers.Authorization = token;
            }
            return config;
        },
        err => {
            return Promise.reject(err);
        });
    
    // http response 服务器响应拦截器,这里拦截401错误,并重新跳入登页重新获取token
    Axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        // 这里写清除token的代码
                        router.replace({
                            path: 'login',
                            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                        })
                }
            }
            return Promise.reject(error.response.data) 
        });
    Axios.interceptors.request.use(config => {
      MintUi.Indicator.open({
        text: '加载中...',
        spinnerType: 'fading-circle'
      });
      return config;
    })
    Axios.interceptors.response.use(response => {
      MintUi.Indicator.close();
      return response;
    })

    post方法封装资料:

    https://blog.csdn.net/hant1991/article/details/74931158

    https://blog.csdn.net/u010214074/article/details/78851093

    可借助 vue-axios 组件库

    完全封装:

    https://www.cnblogs.com/zczhangcui/p/9347447.html

  • 相关阅读:
    SSH框架测试
    Top 20 IoT Platforms in 2018
    基于Helm和Operator的K8S应用管理
    五大开源 Web 代理服务器横评:Squid、Privoxy、Varnish、Polipo、Tinyproxy
    Https单向认证和双向认证
    CNCF Landscape Summary
    走,去出海,一起“Copy to World” | 36氪出海行业报告
    猎豹全球智库执行院长:中国App出海的三大规律和最具代表的五大垂直品类
    闷声发大财,中国 App 出海编年史及方法论
    软件出海的四种模式
  • 原文地址:https://www.cnblogs.com/xiaoyaoxingchen/p/8743781.html
Copyright © 2011-2022 走看看