首先简单了解什么是Axios?
Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js中发送HTTP请求。它支持各种HTTP请求方法,如GET、POST、PUT、DELETE等,并且可以拦截请求和响应,本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范。
关于axios的特点,可以查看axios中文文档,还可以了解一下axios, ajax和fetch的详细比较内容。
接下来开始安装axios,在项目下执行npm install axios。
之后在main.js中,添加:
import axios from 'axios' //引入
以上完成后就可以使用了,接下来以get请求为例,使用方式如下:
this.axios.get(url).then(res => {
//请求成功,触发then中的函数
console.log(res)
})
.catch(error =>
//请求失败,触发catch中的函数 可省略
console.log(error)
)
它的参数需要写在params属性下,也就是:
//带参数的get请求
let url = "..."
this.$axios.get(url, {
params: {
id: 1
}
})
.then((res) => {
console.log(res) //返回的数据
})
.catch((err) => {
console.log(err) //错误信息
})
POST请求与之类似。