vuejs 解決跨域訪問問題

  vuejs的跨域訪問,其實官網和網上已經有很多教程,主要如下:

To configure the proxy rules, edit dev.proxyTable option in config/index.js. The dev server is usinghttp-proxy-middleware for proxying, so you should refer to its docs for detailed usage. But here's a simple example:

// config/index.js
module.exports = {
  // ...
  dev: {
    proxyTable: {
      // proxy all requests starting with /api to jsonplaceholder
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

The above example will proxy the request /api/posts/1 tohttp://jsonplaceholder.typicode.com/posts/1.

翻譯過來就是在config/index.js下面的proxyTable配置您的服務訪問基本地址,將changeOrigin設置爲true即可,然後在你需要訪問接口的地方,這樣使用,以下是我的工程代碼(前提是你已經安裝了vue-resource,安裝方式是:

vue-resource 導入
還有elementui導入方法都是一樣 這裏就醫vue-resource爲例

1
npm installvue-resource --save

之後在需要導入的js中import還有use

1
2
import VueResource from 'vue-resource'
Vue.use(VueResource)
)

 我的使用方式如下:

/* eslint-disable */
<template>
  <div class="hello" style="background: fuchsia">
    <h1>您登陸{{ msg }}</h1>
    <button v-on:click="showDetails">獲取20服務器上接收所信息</button>
  </div>

</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: ''
    }
  },
  methods: {
    showDetails: function () {
      this.$http.post('api/RMSClient/useradmin/login?password=d90b21c4a61992ff330bade33e84633d&userName=444').then(function (res) {
        console.log(res) // 返回很多的數據,比如執行狀態,url,data等等
        console.log(res.data)// 返回的json數據
        console.log(res.data.message)// json對象裏面的信息
        this.msg = res.data.message
      })
    }
  }
}
</script>
    使用過程中,忘記了接口是get還是post,出現了method is not allowed錯誤,才發現是post的形式,然後使用你剛纔設置的baseURL加後面的形式就可以訪問你服務上的接口了,又搞定一個問題,好多坑,歡迎交流

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