axios

作者: Cynicism_ym | 来源:发表于2018-05-14 00:00 被阅读0次

axios简介

axios基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用,它具有以特征:

  • 在浏览器中发送XMLHttpRequests请求
  • node.js 中发送 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和相应数据
  • 自动转化json数据
  • 客户端支持保护安全

支持览器

axios安装

  • 使用bower:

     bower install axios
    
  • 使用 npm

     npm install axios
    

axios使用

  • get

axios.get('http://xxx.api/xxx?参数=值')
.then(response => {
    //成功
    this.list = response.data.message
 })
.catch(err => {
     //失败
     // console.log(err);
})
  • post

axios.post(url, arg) // arg:`参数名=值&参数1=值&参数2=值`
.then(resp => {
       console.log(resp.data);
       console.log(resp.data.status);
})
.catch(err => {
       console.log(err);
})
  • 拦截器

拦截器会拦截发送的每一个请求,请求发送之前执行request中的函数,
请求发送完成之后执行response中的函数
// 请求拦截器
axios.interceptors.request.use(function (config) {
    // 所有请求之前都要执行的操作

    return config;
  }, function (error) {
    // 错误处理

    return Promise.reject(error);
  });

// 响应拦截器
axios.interceptors.response.use(function (response) {
    // 所有请求完成后都要执行的操作

    return response;
  }, function (error) {
    // 错误处理
    return Promise.reject(error);
  });

相关文章

网友评论

      本文标题:axios

      本文链接:https://www.haomeiwen.com/subject/hmqrdftx.html