vue中是推荐使用axios来发送请求的。而且在vue2.0之后也是使用axios来实现发送ajax请求的。

1. 安装

axios有好几种引用的方式,其中主要包括如下:

使用 cdn:

使用npm

$ npm install axios

使用 bower:

$ bower install axios

使用

1.get请求

mounted: function() {

axios

.get('http://www.mycart:7772/allItems')

.then(response => (

this.items = response.data))

.catch(function (error) { // 请求失败处理

console.log(error);

});

}

带有参数的形式

// 直接在 URL 上添加参数 ID=12345

axios.get('/user?ID=12345')

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

// 也可以通过 params 设置参数:

axios.get('/user', {

params: {

ID: 12345

}

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

2. post请求

let formData = new FormData();

//下面是表单绑定的data 数据

formData.append('skuId', item.skuId);

formData.append('quantity',1);

axios

.post("http://www.mycart:7771/cart",formData)

.then(resp=>{

alert("商品添加购物车成功!");

})

.catch(function (error) { // 请求失败处理

alert("商品添加购物车失败");

});

也可以这样传递参数

axios.post('/user', {

firstName: 'Fred', // 参数 firstName

lastName: 'Flintstone' // 参数 lastName

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

跨域请求

axios 默认是不能进行跨域请求的,而且也没法携带cookie,在vue中需要进行如下配置:

axios.defaults.withCredentials = true;

axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

axios.defaults.crossDomain = true;

然后后端也要进行跨域的设置,比如使用@Crossorigin注解,但是需要注意的是允许访问的域名不能使用通配符*,否则会失效。下面给出后端配置的代码样例:

@CrossOrigin(origins= {"http://www.mycart"}, allowCredentials = "true")

public class ItemController {

......

}

更多推荐

Vue中如何实现ajax请求,VUE中如何发ajax请求