向服务器发送HTTP请求的两种方法:Axios 与 fetch()

首先可以用 fetch() API 发送HTTP请求,由于fetch()是浏览器内建方法,因此不需要额外安装package.

其次也可以安装像 Axios 这样的第三方包,Axios 是一个非常流行的 JavaScript 包,用于从 JavaScript 内部发送 HTTP 请求。

使用 Axios 可以简化代码,同一条HTTP post 请求,如果使用 fetch():

fetch('https://something.firebaseio.com/myapp.json', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: this.enteredName,
    rating: this.chosenRating,
  }),
});

header 属性告诉服务器,我们将为这条请求添加一些数据,这些数据将是 JSON 格式的。body 是将要添加的数据。JSON对象的stringify() 方法将JavaScript对象转换为字符串即JSON格式。

上面的请求如果改成使用 Axios:

import axios from 'axios'; // at the start of your <script> tag, before you "export default ..."
...
axios.post('https://something.firebaseio.com/myapp.json', {
  name: this.enteredName,
  rating: this.chosenRating,
});

但是由于使用Axios要额外安装包,这会增加最终的应用程序的大小。

除此以外,fetch() 和 Axios 都返回 Promise,因此都可以使用 .then().catch() 以及 async / await

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值