zoukankan      html  css  js  c++  java
  • axios的学习与使用

    最近的项目都是使用的vue框架,所以请求都使用了vue官方推荐的axios。

    官方中文介绍

    此处记录一下常用的写法

    • 执行 GET 请求
    // 为给定 ID 的 user 创建请求
    axios.get('/user?ID=12345')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    // 可选地,上面的请求可以这样做
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    实际用例

    this.axios.get('***/edu-upload/token/', {headers: {
                'token': this.$store.state.UserMod.token
              }}
          )
            .then(function (respone) {
              if (respone.status === 200) {
                console.log(respone)
                me.uploadInfo = respone.data
                me.uploadFile(file,me)
              }
            })
            .catch(function (error) {
              console.log(error)
            })
    • 执行 POST 请求
    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    实际用例

    this.axios.post(url_pref + '/release/add', JSON.stringify(params),
            {headers: {'Content-Type': 'application/json', 'token': this.$store.state.UserMod.token}})
            .then(function (respone) {
              if (respone.status === 200 && respone.data.code == 0) {
                console.log(respone)
                me.handleOkBtn()
              } else {
                alert("发布失败!");
              }
            })
            .catch(function (error) {
              console.log(error)
              me.$notify.error({
                title: '错误',
                message: '发布备课失败!'
              })
            })
    • 执行多个并发请求
    function getUserAccount() {
      return axios.get('/user/12345');
    }
    
    function getUserPermissions() {
      return axios.get('/user/12345/permissions');
    }
    
    axios.all([getUserAccount(), getUserPermissions()])
      .then(axios.spread(function (acct, perms) {
        // 两个请求现在都执行完成
      }));

    axios API

    可以通过向 axios 传递相关配置来创建请求

    axios(config)

    // 发送 POST 请求
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });

    axios(url[,config])

    // 发送 GET 请求(默认的方法)
    axios('/user/12345');
  • 相关阅读:
    查看 FormData 中已存在的值
    dedecms 后台可以上传mp4,但无法选择
    dedecms 文章根据 权重排序
    js 单行注释
    dedecms给图片加水印覆盖整张图片
    Nginx服务器 配置 https
    dedecms 后台 菜单点击后打开的慢
    用 PHP文件引入css样式
    TFT、LCD、OLED、LPTS、CRT等显示屏的区别
    ORCAD中的一些操作小技巧
  • 原文地址:https://www.cnblogs.com/shenting/p/10414294.html
Copyright © 2011-2022 走看看