学习记录——axios

1. axios基本使用

  • getdelete请求传递参数:
    • 传统形式:url?的形式传递参数
    • restful形式:通过params形式传递参数
  • postput请求传递参数:
    • 通过选项传递参数
    • 通过URLSearchParams传递参数

2. 发送get请求

axios.get('http://localhost:3000/adata').then(function (ret) {
	//拿到 ret 是一个对象      所有的对象都存在 ret 的data 属性里面
	// 注意data属性是固定的用法,用于获取后台的实际数据
	// console.log(ret.data)
	console.log(ret);
});

3. get请求传递参数

1. 通过传统的url?的形式传递参数

axios.get('http://localhost:3000/axios?id=123').then(function (ret) {
	console.log(ret.data);
});

2. restful形式传递参数

axios.get('http://localhost:3000/axios/123').then(function (ret) {
	console.log(ret.data);
});

3. 通过params形式传递参数

axios
	.get('http://localhost:3000/axios', {
		params: {
			id: 789,
		},
	})
	.then(function (ret) {
		console.log(ret.data);
	});

4. delete请求传参

传参的形式和get请求一样

axios
	.delete('http://localhost:3000/axios', {
		params: {
			id: 111,
		},
	})
	.then(function (ret) {
		console.log(ret.data);
	});

5. post请求

1. 通过选项传递参数

axios
	.post('http://localhost:3000/axios', {
		uname: 'lisi',
		pwd: 123,
	})
	.then(function (ret) {
		console.log(ret.data);
	});

2. 通过URLSearchParams传递参数

var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function (ret) {
	console.log(ret.data);
});

6. put请求传参

传参的形式和get请求一样

axios
	.put('http://localhost:3000/axios/123', {
		uname: 'lisi',
		pwd: 123,
	})
	.then(function (ret) {
		console.log(ret.data);
	});

7. axios全局配置

// 配置公共的请求头 
axios.defaults.baseURL = 'https://api.example.com';
// #配置 超时时间
axios.defaults.timeout = 2500;
// 配置公共的请求头
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

8. axios拦截器

1. 请求拦截器

请求拦截器的作用是在请求发送前进行一些操作。例如在每个请求体里加上token,统一做了处理如果以后要改也非常容易

axios.interceptors.request.use(
	function (config) {
		console.log(config.url);
		//  1.1 任何请求都会经过这一步   在发送请求之前做些什么
		config.headers.mytoken = 'nihao';
		//  1.2 这里一定要return   否则配置不成功
		return config;
	},
	function (err) {
		//  1.3 对请求错误做点什么
		console.log(err);
	}
);

2. 响应拦截器

响应拦截器的作用是在接收到响应后进行一些操作。例如在服务器返回登录状态失效,需要重新登录的时候,跳转到登录页

axios.interceptors.response.use(
	function (res) {
		//  2.1 在接收响应做些什么
		var data = res.data;
		return data;
	},
	function (err) {
		//  2.2 对响应错误做点什么
		console.log(err);
	}
);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火星飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值