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>

執行請求, 成功返回結果

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