AntDesign vue學習筆記(二)axios使用


之前在vue頁面中引入axios使用,本篇在mainjs中引入,這樣就不用單獨在每個頁面引入

1、mainjs中引入axios,設置基礎url

import axios from 'axios'
axios.defaults.baseURL = 'https://localhost:8080/'
Vue.prototype.axios = axios

2、在vue頁面中,注意axios前需要加this.

methods: {
    login () {
      let that = this
      console.log(this.userName)
      console.log(this.password)
      this.axios
        .get('/api/login', {
          params: {
            userName: that.userName,
            password: that.password
          }
        })
        .then(function (response) {
          console.log(response)
          if (response.data.data.result === 'success') {
            that.$router.push('second')
          } else {
            alert(response.data.data.message)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }

3、function (response)中必須使用that才能獲取到$router對象,有沒有辦法直接獲取到呢,代碼如下

 methods: {
    login () {
      let that = this
      console.log(this.userName)
      console.log(this.password)
      this.axios
        .get('/api/login', {
          params: {
            userName: that.userName,
            password: that.password
          }
        })
        .then((response) => {
          console.log(response)
          if (response.data.data.result === 'success') {
            this.$router.push('second')
          } else {
            alert(response.data.data.message)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }

ES6中的 箭頭函數 "=>" 內部的this是詞法作用域,由上下文確定(也就是由外層調用者vue來確定)。

4、關於api/login,api login是模擬的一個json數據

4.1在項目根目錄下添加data.json,內容如下

{
    "loginresult": {
      "result": "success",
      "message": ""
    }
}

4.2修改webpack.dev.conf.js文件,添加紅色部分代碼,關閉服務器重新npm run dev.

4.3、點擊登錄按鈕就可以工作了。

5、如果傳遞比較復雜的請求,比如header添加數據,方法如下

this.axios(
        {
          method:"post",
          url:'/api/Login', 
          data:{
            username: that.userName,
            password: that.password
          }, 
          headers: {
            'Content-Type':'application/json;charset=UTF-8'
          }
        })
        .then((response) => {
          console.log(response)
        })
        .catch(function (error) {
          console.log(error)
        })
    }

6、配置跨域的方法

找到config/index.js添加如下代碼

proxyTable: {
        '/api': {
            target: 'http://xx.xx.xx.xx:8080/',
            changeOrigin: true,
            pathRewrite: {'^/api': '' }
        }
    
  }

這樣所有訪問api接口都會走這個重定向。

7、跨域下接口兩次請求處理屏蔽方法

1、可以在后端設置Access-Control-Max-Age
2、或者請求限制只允許Post,Get.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM