axios的学习与使用
本次系统分析与设计期末挣闲钱项目,我负责前端部分的实现。按照项目要求文档中的描述,我使用了vue这一JavaScript框架来完成前端界面的实现。为了实现前后端之间的通信,使用了axios。axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端。 它具有以下特征:从浏览器中创建 XMLHttpRequest从 node.js 发出 http 请求支持 Pr...
·
本次系统分析与设计期末挣闲钱项目,我负责前端部分的实现。按照项目要求文档中的描述,我使用了vue这一JavaScript框架来完成前端界面的实现。
为了实现前后端之间的通信,使用了axios。axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端。 它具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
本篇博客主要介绍axios的相关内容。
安装
-
类似于iVew的安装:
- 使用 “npm install axios --save”进行下载安装。
基本内容:
-
网上样例:
axios.get('/user?ID=12345').then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); // 通过 params 对象传递参数 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时,需要在main.js中导入axios并将其写入vue原型。
axios.defaults.baseURL = 'http://172.18.32.30:3000' axios.defaults.withCredentials = true; Vue.prototype.$axios = axios;
-
在项目中使用axios获取用户信息,使用response.data读取JSON数据,url为后端写好的api的url:
getUserInfo(){ let vm = this; this.$axios.get(url, { }) .then(function(response) { let data = response.data; if (data.code == 200) { let userInfo = data.data; vm.username = userInfo.username; vm.getTasks(vm.typeSelect); } }) .catch(function (error) { if (error.response.status == 401) { vm.$Notice.warning({ title: '错误', desc: "请重新登录" }); vm.$router.push({name: 'login'}); } }); },
-
post方法与get类似。
更多推荐
已为社区贡献1条内容
所有评论(0)