vue cli2.0利用proxyTable跨域详细教程,附带前后端实例

配置目录:config>index.js
配置:

    proxyTable: {
      '/api': { //代理
        target: 'http://172.30.34.180:3000/',//服务端地址和端口
        changeOrigin: true,//启动代理
        pathRewrite: {//重写路径
          '^/api': ''
        }
      }
    },

测试代码前端代码:

<template>
  <div>
    <button @click="test">测试</button>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  methods: {
    test () {
      axios.get('/api/').then(res => {
        console.log(res)
      })
    }
  }
}
</script>

测试后端nodejs代码片段:

var fn_index = async (ctx, next) => {

  console.log(html)
  ctx.response.body = {
    state: 200,
    data: {
      list: [{ userName: "张三", id: 3 }, { userName: "李四", id: 4 }]
    }
  };
  console.log(ctx.response)
};

服务端端口3000
效果图:
vue cli2.0利用proxyTable跨域详细教程,附带前后端实例

成功跨域!
提示:上线时需要把代理的服务器改为线上的服务器。