參考文檔:
https://www.jb51.net/article/125717.htm
使用axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基本使用方法:
get請求:
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Post請求:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
簡單示例:
// 在進行 post 和 get 請求的時候,使用 axios 進行訪問 // 進行 get 請求 axios.get(url).then(function (response){ console.log(response); }).catch(function(error){ console.log(error); }); // 進行post 請求 axios.post(url,{firstName:'Fred',lastName:'Flintstone'}).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); });
這樣發送請求,雖然是可以發送,但是攜帶的參數,是一個json字符串,會出現問題。所以我們在用post發送請求的時候,需要這樣:
axios({ method:'post', url:url, data:{title:this.title,content:this.content}, headers:{'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } }).then((res)=>{ console.log(res.data); });
上面這種只能提交一些簡單的數據,對於復雜的數據,可以考慮使用 QS 對數據進行處理。
使用方法,如果找不到QS文件,可以只用 npm 安裝:
npm install qs
下載這個文件之后,使用 script 標簽正常引入即可。
使用方法:
var formData = Qs.stringify({imgIds: [48,49],});
axios.post(url,Qs.stringify(this.formData)).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); });
或者是:
axios({ method: 'post', url:url, data:Qs.stringify(this.formData), }).then((res)=>{ console.log(res); });