VUE学习笔记(五) 引入axios

VUE学习笔记(一)   环境

VUE学习笔记(二) Visual Studio Code

VUE学习笔记(三) 运行VUE

VUE学习笔记(四) 引用element-ui

VUE学习笔记(五) 引入axios

Axios 是一个基于 promise 的 HTTP 库

VUE前端与服务端进行数据交互, 通常使用 axios

 

安装axios

npm install --save vue-axios

 

安装成功

引入axios

在main.js中加入

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

 

下一步, 需要验证一下请求是否能成功

自行准备Get 和 Post 环境

测试一
URL:http://localhost:57541/act/getPerson
方式:GET
参数:id=1
返回:{"name":"奇犽","age":"15","ability":"暗歩"}

测试二
URL:http://localhost:57541/act/getPet
方式:POST
参数:id=1
返回:{"name":"闪电狗","age":"200","ability":"闪电"}

修改HelloWorld.vue如下

<template>
  <div>
    <el-button @click="doget">getTest</el-button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {};
  },
  methods: {
    doget() {
      let url = "http://localhost:57541/act/getPerson";
      let params = { id: 1 };
      this.axios
        .get(url, { params })
        .then(function(res) {
          console.log(res);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
};
</script>

点击测试

并没有成功返回数据, 出现了跨域的问题.

那么先解决跨域.

修改config/index.js 中的 proxyTable

 proxyTable: {
      "/act": {
        target: "http://localhost:57541/", //后端接口地址
        changeOrigin: true, //是否允许跨越
        pathRewrite: {
          "^/act": "/act" //重写,
        }
      }
    },

修改配置文件要重启终端

ctrl+c 停止终端, npm run dev , 重新启动终端,

点击测试

执行成功

成功返回结果

继续修改HelloWorld.vue, 来测试Post请求

<template>
  <div>
    <el-button @click="doget">getTest</el-button>
    <el-button @click="dopost">postTest</el-button>
    <p>getMsg:{{ getMsg }}</p>
    <p>postMsg:{{ postMsg }}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      getMsg: "",
      postMsg: ""
    };
  },
  methods: {
    doget() {
      let This = this;
      let url = "/act/getPerson";
      let params = { id: 1 };
      This.axios
        .get(url, { params })
        .then(function(res) {
          console.log(res);
          This.getMsg = res.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    dopost() {
      let This = this;
      let url = "/act/getPet";
      let params = { id: 1 };
      This.axios
        .post(url, params )
        .then(function(res) {
          console.log(res);
          This.postMsg = res.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
};
</script>

执行请求, 成功返回结果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章