本次系统分析与设计期末挣闲钱项目,我负责前端部分的实现。按照项目要求文档中的描述,我使用了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类似。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐