axios发送Post和get请求

1.安装

node方式

npm install axios

设置index.js

import axios from ‘axios’

Vue.prototype.$ajax = axios

或者使用cdn方式:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2.post请求

	axios.post('/user', {
		 firstName: 'Fred',
		 lastName: 'Flintstone'
	})
	.then(function (response) {
	 	console.log(response);
	})
	.catch(function (error) {
	 	console.log(error);
	});

注意:对于post请求,一般情况下,第一个参数是url,第二个参数是要发送的请求体的数据,第三个参数是对请求的配置。

3.get请求

	axios.get('/user?ID=12345')
	 .then(function (response) {
	  console.log(response);
	 })
	 .catch(function (error) {
	  console.log(error);
	 });
	 
	axios.get('/user', {
	  params: {
	   ID: 12345
	  }
	 })
	 .then(function (response) {
	  console.log(response);
	 })
	 .catch(function (error) {
	  console.log(error);

对于get请求,也可以使用axios.get()的形式,如下:

axios.get('/bbg/shop/get_classify', {
params: {
sid: 15687425
},
headers: {
"BBG-Key": "ab9ef204-3253-49d4-b229-3cc2383480a6"
}
})
.then(function (response) {
if (response.data.code == 130) {
items = response.data.data;
store.commit('update', items);
console.log(items);
}
console.log(response.data.code);
}).catch(function (error) {
console.log(error);
console.log(this);
});

即第一个参数是:url, 第二个参数就是一个配置对象,我们可以在配置对象中设置 params 来传递参数。

4.执行多个请求:

function getUserAccount() {
	return axios.get('/user/12345');
	}
	 
	function getUserPermissions() {
	 return axios.get('/user/12345/permissions');
	}
	 
	axios.all([getUserAccount(), getUserPermissions()])
	 .then(axios.spread(function (acct, perms) {
	  // Both requests are now complete
	 }));

你可能感兴趣的:(axios发送Post和get请求)