首页 > 其他 > 详细

Vue跨域问题解决方案

时间:2021-03-27 12:26:45      阅读:14      评论:0      收藏:0      [点我收藏+]

前端和后端在不同机器上开发,前端请求后台数据时出现跨域问题

解决方案:

方法一(无效):

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);
          })

Vue跨域问题解决方案

原文:https://www.cnblogs.com/lxy3/p/14585185.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!