- 直接在控制台上打印axios会报错,打印fetch就不会;
- 因为fetch是标准,axios是第三方,要想用axios,就必须引入想应的js文件;
- axios-js文件下载:npm
- 搜索axios,点进去,往下找:
- 打开链接:“https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js”,ctrl+s保存源码,就下载好了;
- 然后引入到html中就可以使用了。
get方式:axios请求数据核心代码
axios.get("./test.json").then(res => {
console.log(res)
//数据在res.data.data.films里
console.log(res.data.data.films)
})
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../lib/vue.js"></script>
<script src="axios.min.js"></script>
</head>
<body>
<div id="box">
<button @click="handleClick">axios</button>
</div>
<script>
new Vue({
el:"#box",
data:{
},
methods:{
handleClick(){
axios.get("./test.json").then(res => {
console.log(res)
//数据在res.data.data.films里
console.log(res.data.data.films)
})
}
}
})
</script>
</body>
</html>
结果:
post方式:不用写headers
携带的信息放在第二个参数位置上就可以了,不用写其他的;
handleClick(){
axios.post("./test.json","name=yiyi&age=100").then(res => {
console.log(res)
//数据在res.data.data.films里
console.log(res.data.data.films)
})
}
axios.post("./test.json",{name:"yiyi",age:100})
- axios请求数据的方式比fetch方式更简单,直接一个then就可以;
- 而且post方式还不用写headers,直接写数据,会自动查看你携带的数据是什么类型;