最近通过 Vuejs 重构旅游页面项目使用到 axios 获取数据。对照官方文档,简要记录一些 axios 的使用方法和特性,方便日后参考和查阅。
axios
阿克西奥斯。基于 promise
用于浏览器和 node.js
的 http
客户端
安装
npm 安装
npm install axios
通过 cdn 引入
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.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);
});
执行多个并发请求
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) {
// 两个请求现在都执行完成
}));
其他
设置 mock数据 开发环境转发代理
在 Vue-cli 脚手架工具之下
设置 config
文件夹下的 index.js
设置 module.exports
下 dev
的 proxyTable
代理
webpack-dev-server 工具会自动将 /api
替换成 /static/mock
从而达到不用改动项目代码的目的
proxyTable: {
'/api': {
target: 'http://localhost:8080',
pathRewrite: {
'^/api': '/static/mock'
}
}
}
网友评论