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 install vue-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加后面的形式就可以访问你服务上的接口了,又搞定一个问题,好多坑,欢迎交流

猜你喜欢

转载自blog.csdn.net/omayyouhappy/article/details/79082752