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])

扫描二维码关注公众号,回复: 5259523 查看本文章
// 发送 GET 请求(默认的方法)
axios('/user/12345');

猜你喜欢

转载自www.cnblogs.com/shenting/p/10414294.html
今日推荐