您的位置:首页 > Web前端 > Vue.js

vue简学之路(案例二)axios请求get及post以及全局拦截器

2020-01-15 10:13 344 查看

axios请求
在这里要先安装axios,我的例子是直接引入网上的

命令如下 npm install axios 可使用的idea直接安装

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios请求</title>
<script src="vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<!--使用axios請求獲得文件內容-->
<div  id="app">
<h1>
{{msg}}
</h1>
<button @click="getmsg()">click</button>
<button @click="postmsg()">postclick</button>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
msg:""
},
//生命周期函数,组件在被挂载的时候调用
mounted(){
//全局拦截器,可以对请求修改
axios.interceptors.request.use(function(config){
console.log("请求马上就要发出了,在拦截请求之前发送")
return config
})
axios.interceptors.response.use(function (response) {
console.log(response)
response.data="修改为董国庆"
console.log("拦截到响应")
return response
})
},

methods:{
//請求
getmsg:function()
{
// 需要npm安装axios
axios.get("./test.txt",{params:{id:1},headers:{token:"123"}}).then(res=>{
this.msg=res.data
console.log("ok")
}).catch(res=>{
console.log(err)
})
},
postmsg:function()
{

axios.post("./test.txt",{name:"admin",age:18}).then(res=>{
console.log("ok")
}).catch(res=>{
console.log(err)
})
}

}
})
</script>

</body>
</html>
  • 点赞
  • 收藏
  • 分享
  • 文章举报
一座孤岛 发布了22 篇原创文章 · 获赞 3 · 访问量 808 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: