axios前后端交互

今天有点儿累了,由于工作失误,导致今晚不开心,今天不想写了… …

axios的基本用法

get请求用法
// 请求一个给定的用户ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // 请求处理结果
    console.log(response);
  })
  .catch(function (error) {
    // 请求处理错误
    console.log(error);
  })
  .then(function () {
    // 成功与否总是执行
  });
  • 上面的请求也可以这样写
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    
  });  
  • 使用es7异步写法
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
post用法
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });

关于拦截器

  • 请求拦截器:在请求之前去对一些请求工作进行统一的配置
axios.interceptors.request.use(function (config) {
    // 请求之前做一些事情
    return config;
  }, function (error) {
    // 请求错误做一些事情
    return Promise.reject(error);
  });
  • 响应拦截器:在请求成功后做一些统一事情
axios.interceptors.response.use(function (response) {
    // 状态码是2xx,都会导致该函数触发
    // 做一些响应数据事情
    return response;
  }, function (error) {
    // 状态码不是2xx都会触发这个函数
    // 做一些错误响应的事情
    return Promise.reject(error);
  });
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值