Nodejs笔记---对Axios的理解以及基本用法

最近在学习的过程中接触到了Axios,写下本文记录一下。

1、Axios。在npmjs.com上:https://www.npmjs.com/package/axios。对axios的用法有了比较详细的介绍。

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。以下是其支持的浏览器

不难看出,大部分的浏览器都是支持的,接下来介绍一下用法。

2、Axios的用法

安装axios:npm install axios --save

2.1、执行get请求:创建给定aid和bid的get请求

axios.get('/test?aid=12345&bid="abc"')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

还能通过json传送变量,上面的请求可以换成下面的样子

axios.get('/test', {
    params: {//这里可以放你想要传的变量,这样看起来爽多了
      aid: 12345,
      bid:abc
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 2.2、执行post请求

axios.post('/test', {
    aid: '123',
    bid: 'ABC'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

当然,axios的功能不仅仅这样,还可以处理并发请求,看下面

function firstResquest() {
  return axios.get('/test/123');
}

function secondResquest() {
  return axios.get('/test/abc');
}

axios.all([firstResquest(), secondResquest()])
  .then(axios.spread(function (first, second) {
    // 两个请求都执行完成
  }));

//简直是一举双雕啊

 当然我比较喜欢的是下面的方式,通过向axios传送相关的配置来做相应的请求,因为在大多数情况下我们的请求是多样的,所以用下面的方式。。。嗯,很棒。。。

首先我们定义后配置:config

var config = {
    method: 'post',
    url: '/test/12345',
    data: {//传递的参数
        aid: '123',
        bid: 'abc'
    }
    headers: {//指定响应头
        "Content-Type": "application/json;charset=utf-8",
        "Accept": "application/json"
    }
}
axios(config);

这样看起来爽多了,后期还可以再封装一下。

就写这么多吧,对axios感兴趣的话,建议去看一下https://www.npmjs.com/package/axios,这里讲的比较全面

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值