axios插件使用

什么是axios?

axios使用一个基于promise的http库网络插件,可以在浏览器和node.js中使用。
支持promise API,自动装换JSON数据
安装:

 npm install axios

导入:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用:

//发送get请求
axios.get('地址?id=user')//括号内为地址和参数
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 //上面的代码还可以把参数单独出来
 axios.get('地址', {
    params: {
      id: user
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
//发送post请求
axios.post('地址', {
    key: 'value',//这个为发送post的参数
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

响应请求的结构

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}
//获取响应的内容
axios.get('地址')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

配置默认值

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//默认请求类型
axios.defaults.timeout = 2500;
//默认超时时间
axios.defaults.baseURL="http://127.0.0.1";
//默认根地址,有了默认根地址后,后面在发送请求不用写跟地址,项目上线后可以修改默认根地址

错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值