axios基本用法

什么是Axios
Axios本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范。

params是添加到url的请求字符串中的,常用于get请求,也可以用于post请求
data是添加到请求体(body)中的, 只适用于'put'、'post'、'patch'类型的请求,虽然get请求可以用data,但是很多软件不支持

一. axios的三种写法

// 第一种写法
axios.get('/query?name=tom').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
// 第二种写法
axios.get('/query', {
    params: {
        name: 'tom'
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
// 第三种写法,虽说get请求
axios({
  method: 'get',
  url: '/query',
  data: {
    name: 'tom',
  }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

二. 各种请求的写法

1.get
function axiosGet() {
	axios({
		method: 'get',
		url: 'https://music.benwebsite.cloud/banner',
		headers: {
			'content-type': 'application/json'
		} ,
		params: {
			type: 2 
		}
	}).then(res => {
		console.log('成功');
		console.log(res);
	}).then(err => {
		console.log('err');
	})
}

2.post
function axiosPost() {
	axios({
		method: 'post',
		url: 'https://music.benwebsite.cloud/banner',
		headers: {
			'content-type': 'application/json'
		} ,
		params: {
			type: 2 
		}
	}).then(res => {
		console.log('成功');
		console.log(res);
	}).then(err => {
		console.log('err');
	})
}

3.put
function axiosPut() {
	axios({
		method: 'put',
		url: 'https://music.benwebsite.cloud/banner',
		headers: {
			'content-type': 'application/json'
		} ,
		params: {
			type: 2 
		}
	}).then(res => {
		console.log('成功');
		console.log(res);
	}).then(err => {
		console.log('err');
	})
}

4.delete
function axiosDelete() {
	axios({
		method: 'delete',
		url: 'https://music.benwebsite.cloud/banner',
		headers: {
			'content-type': 'application/json'
		} ,
		params: {
			type: 2 
		}
	}).then(res => {
		console.log('成功');
		console.log(res);
	}).then(err => {
		console.log('err');
	})
}

posted @ 2022-10-21 14:35  坚强的小蚂蚁  阅读(379)  评论(0编辑  收藏  举报