vue-resource
vue-resource 是 Vue.js 的插件,提供了使用 XMLHttpRequest 或 JSONP 進行 Web 請求和處理響應的服務。 當Vue.js 更新到 2.0 之後,作者就宣告不再對 vue-resource 進行更新,而是推薦 axios。
axios
axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
引入 axios
使用 npm
$ npm install axios
使用 bower
$ bower install axios
使用 cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
get 請求
// 爲給定 ID 的 user 創建請求
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);
});
post 請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
請求方法的別名
爲方便起見,爲所有支持的請求方法提供了別名
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.options(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])