学习文档:https://www.jianshu.com/p/9359bf779376
Promise:https://blog.csdn.net/z591102/article/details/108510315
axios是基于promise管理ajax请求库
安装:
利用yarn安装 : yarn add axios,如果显示yarn没有找到该命令,则需要安装npm install -g yarn
利用npm安装 : npm install axios --save
利用bower安装 : bower install axios --save
利用cdn引入 : <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
实例全局配置
// npm i axios import axios from 'axios' const http = axios.create({ baseURL: process.env.VUE_API_APP_URL, timeout: 1000, })
axios常用请求方法
get 获取数据
post 提交数据
put 更新数据(所有数据推送到后端)
patch 更新数据(只将修改的数据推送到后端)
delete 删除数据
GET
axios.get('/data.json',{ // 注 此处参数写入params中 ---get请求需要用到params params: { id: 'zxm' } }).then(res => { console.log(res); })
POST
// post:参数直接跟在url后面即可 axios.post('xxxxxxxxx', { xxx: 'xxxx', xxxx: 'xxxx' } }).then(res => { console.log(res); })
put请求 ---上面get,post为简单写法
axios({ method: 'PUT', url: " http://localhost:3000/persons/1", data: { name:'dyk12', age:8 } }).then((response) => { console.log(response.data) });
delete请求
axios({ method: 'DELETE', url: "http://localhost:3000/persons/1", }).then((response) => { console.log(response.data) });
并发请求:
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) { // 两个请求现在都执行完成 }));
拦截器
// 添加请求拦截器 const reqInterceptor = axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); }); // 添加响应拦截器 const resInterceptor = axios.interceptors.response.use(function (response) { return response; }, function (error) { return Promise.reject(error); }); // 移除拦截器 axios.interceptors.request.eject(reqInterceptor); axios.interceptors.request.eject(resInterceptor);标签:function,axios,return,请求,get,response From: https://www.cnblogs.com/xinyu-yudian/p/16760587.html