首先可以用 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
。