上一篇内容讲到在符合W3C标准的浏览器可以直接来使用这个fetch做请求,那么使用vue呢,前面内容也提到推荐使用这个axios第三方库,axios的使用也是非常的方便的,下面来对axios进行了解,了解之后就能够结合上一篇fetch的内容进行对比,知道为啥用这个axios。
axios
Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js,本质也是对XHR的封装;同样我们通过点击按钮来发起请求,这里我们是尚未讲到在项目当中的使用,所以不用npm命令安装使用,进行script的引入使用;
页面中引入 axios :
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
通过axios完成上次 fetch 所完成的效果,这里仅需要将fetch改成axios的请求方式即可;
axios.get 请求
进行请求上一篇内容所模拟请求的json数据;打印的数据res.data就是模拟的数据;
-
methods:{
-
handleClick(
){
-
axios.
get(
"fetch.json")
-
.
then(
res=>{
-
// console.log(res);
-
console.
log(res.
data);
-
})
-
}
-
}
将取来的数据赋值给data中的List,通过v-for指令将数据在页面中进行渲染;具体页面代码可以看上一篇内容的代码;
-
data:{
-
List:[]
-
},
-
methods:{
-
handleClick(
){
-
axios.
get(
"fetch.json")
-
.
then(
res=>{
-
console.
log(res.
data);
-
this.
List = res.
data.
List
-
})
-
}
-
}
以上就是一个简单的axios做get请求;
axios.post 请求
上一篇内容讲到做post请求时,有两种编码格式,这里重新回顾一下fetch做post请求的代码;
application/x-www-form-urlencoded
-
handleClick(
){
-
fetch(
"请求地址",{
-
method:
'POST',
// 请求方式
-
headers:{
"Content-Type":
"application/x-www-form-urlencoded" },
-
body:
"name=li&age=18"
-
},
-
)
-
.
then(
res=>res.
json())
-
.
then(
res=>{
console.
log(res);})
-
}
application/json
-
handleClick(
){
-
fetch(
"请求地址",{
-
method:
'POST',
// 请求方式
-
headers:{
"Content-Type":
"application/json" },
-
body:
JSON.
stringify({
-
name:
"zs",
-
age:
18
-
})
-
},
-
)
-
.
then(
res=>res.
json())
-
.
then(
res=>{
console.
log(res);})
-
}
通过以上两端在fetch请求中的操作,可以看出需要写的东西比较多的,那么使用axios是不需要写这么多的,下面来看看axios中的post请求方法的用法:
-
// axios.post(参数1,参数2).then(res=>{console.log(res.data)})
-
// 参数1:请求地址
-
// 参数2:
-
-
1)axios.
post(
"****请求地址****",
"name=zs&age=18")
-
.
then(
res=>{
-
console.
log(res.
data);
-
})
-
-
"name=zs&age=18"提交后的就是对应的是 application/x-www-form-urlencoded
-
-
2)axios.
post(
"****请求地址****",{
-
name:
"zs",
-
age:
18
-
})
-
.
then(
res=>{
-
console.
log(res.
data)
-
})
通过这两种方式对比就能知道axios的使用比起fetch要简便不少;
axios 小用一下
以上的一个案例是通过我们自己模拟的数据来进行的,下面通过一些比较实在可靠的一些后端数据来做一个测试,用以下的这个API可以获取一些后端数据;
https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%8F%A0%E6%B5%B7&ci=108&channelId=4
内容的数据是比较多的,取hot数据当中的数据复制下来作为接下来要请求json的数据;这样能够去使用拿到真实数据然后进行练习;
将数据复制给到文件当中的 axios.json文件当中来;然后通过axios.get请求相应的数据;
点击 axios 按钮获取数据,在控制台上打印,能看到请求回来的数据相对模拟的数据更加真实;
-
handleClick(
){
-
axios.
get(
"axios.json")
-
.
then(
res=>{
-
console.
log(res);
-
})
-
}
通过res.data拿到我们想要的数据并简单的输出其中的一些数据;
-
data:{
-
hot:[]
-
}
-
methods:{
-
handleClick(
){
-
axios.
get(
"axios.json")
-
.
then(
res=>{
-
this.
hot = res.
data.
hot
-
})
-
}
-
}
以上就是本篇 axios 使用的一个基本内容;结合上一篇fetch可以理解到fetch和axios的一些区别和应用,通过这两篇的内容能够对如何来发送数据请求获取响应数据有一个基础的认识!内容仅仅是基础,后续有的话会在项目当中进行详说!感谢观看!
转载:https://blog.csdn.net/weixin_52203618/article/details/127503663