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]])