axios获取后端数据以及全局拦截器

本文介绍了axios的基础应用,包括如何利用axios获取后端数据,同时探讨了在实际开发中如何设置axios的全局拦截器,以处理如post请求的状态等关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

axios的基础知识
在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
	<title>vue-axios插件的讲解</title>
	<script src='node_modules/vue/dist/vue.js'></script>
	<script src='node_modules/vue-resource/dist/vue-resource.js'></script>
	<script src='node_modules/axios/dist/axios.js'></script>
</head>
<body>
	<div id="app">
		<a href="#"  v-on:click="get">Get请求</a>
		<a href="#" @click="post">Post请求</a>
		<a href="#" @click="http">http请求</a><br>
		<span>{{msg}}</span>
	</div>
	<script>
		new Vue({
			el:"#app",
			data:{
				msg:''
			},
			//全局拦截器
			mounted: function(){
				axios.interceptors.request.use(function(config){console.log("1")
					return config;})
				axios.interceptors.response.use(function(response){console.log("2")
					return response;})
			},
			methods:{
				//get请求get(url, [options])
				get: function(){
					axios.get("package1.json",{
						params:{// [options]
							userId:"999",
						},header:{
							token:"jack",
						},
					}).then(res=>{this.msg=res.data})
					.catch(error=>{
						console.log(error)
					})
				},
                //post请求post(url, [body], [options])
				post: function(){
					axios.post("package.json",{
						//[body]
						userId:888
					},{//[options]
						headers:{
							token:"tom"
						}
					}).then(res=>{
						this.msg=res.data;
					}).catch(error=>[
					console.log(error)])	
				},
				http:function(){
					axios({
						url:"package.json",
						method:"get",
						//post的数据直接写在data里面
						data:{
							userId:"101"
						},
						//get的数据直接写在params里面
						params:{
							userId:"102"
						},
						headers:{
							token:"http-test"
						}
					}).then(res=>{
					this.msg=res.data})
				}
			
			}
		})
	</script>
</body>
</html>

post请求在全局拦截器下的状态
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值