前端和后端在不同机器上开发,前端请求后台数据时出现跨域问题
解决方案:
方法一(无效):
1.安装axios,并在main.js中引用
import axios from 'axios'
Vue.prototype.$axios=axios;
2.在根目录下创建vue.config.js文件
![]()
3.在vue.config.js文件中配置
module.exports = {
  devServer: {
    open: true,
    host: 'localhost',
    port: 8080,
    https: false,
    hotOnly: false,
    proxy: {
      // 配置跨域
      '/api': {
        target: 'http://192.168.1.105:8081',//后端接口地址
        ws: true,
        changOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    before: app => {}
  }
};
4.请求数据
this.$axios.get('/api/test')
//最后请求的地址会是http://192.168.1.105:8081/hello,但我测试还是localhost,无效
方法二:
1.安装axios,并在main.js中引用
import axios from 'axios'
Vue.prototype.$axios=axios;
2.直接配置在config文件下index.js的proxyTable中
![]()
module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/': {
        target: 'http://192.168.1.105:8081',//后端接口地址
        changOrigin: true,
        pathRewrite: {
          '^/': '/'
        }
      }
    }
  }
}
3.就可以请求到数据了
this.$axios.get('/hello').then(res=>{
            console.log(res);
          })