vue axios详细攻略
axios简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端
功能特性
- 在浏览器中发送 XMLHttpRequests 请求
- 从 node.js 发出 http 请求
- 支持 Promise API
- *拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
安装axios
$ npm install axios
$ cnpm install axios //taobao源
或者使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
安装完成后在main.js中增加一下配置:
import axios from 'axios';
Vue.prototype.$axios = axios;
axios.defaults.withCredentials=true;
/*axios默认是请求的时候不会带上cookie的,需要通过设置 withCredentials:true来解决。*/
目的:使用vue-cli构建的项目,在开发时,想要访问后台接口获取数据,这时就会出现跨域问题。
在config/index.js中进行如下配置
详细用法
发送一个 GET 请求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
/*请求URL 发送参数 回调函数 错误
发送一个 POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
/*请求URL 发送参数 回调函数 错误
发送多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
axios API
可以通过给 axios传递对应的参数来定制请求:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});