一、什么是axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
我的简单理解就是axios用来向后台发请求。
二、基础用法:
1、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); }); |
2、post请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3、多个并发请求
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) { // 两个请求现在都执行完成 })); |
三、axios在vue项目中
在src文件夹下新建一个apis文件夹,然后新建一个api.js文件,存放内容如下:
(1)引入axios,编写可调用接口
(2)在组建中使用
引入api.js中的接口,然后再对应的方法中传参使用,具体如下: