vue中是推薦使用axios來發(fā)送請求的。而且在vue2.0之后也是使用axios來實現發(fā)送ajax請求的。
1. 安裝
axios有好幾種引用的方式,其中主要包括如下:
- 使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- 使用npm
$ npm install axios
- 使用 bower:
$ bower install axios
使用
1.get請求
mounted: function() {
axios
.get('http://www.mycart.com: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.com: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.com"}, allowCredentials = "true")
public class ItemController {
......
}