【从0到1打造vue element-ui管理后台 】 第三课 开发环境解决跨域问题

417 阅读1分钟

第三课 开发环境解决跨域问题

一、模拟跨域问题

另外建立一个vue的项目,把data.json拷贝到另一个项目的public中,并且启动起来,我们把这个项目称为测试数据项目,之前项目称为工作项目

二、测试数据启动后,生成json数据地址

http://localhost:8080/data.json   

image.png

三、修改工作项目中的test.js

 getList(){
        const promise1 = myaxios({
            method:'get',
            url:'http://localhost:8080/data.json'
        })
        return promise1
    }

image.png

这样问题就生成了,不在一个端口下,就会报跨域

四、如何解决呢?打开vue.config.js文件,加入devServer.proxy,增加一个中间代理服务器进行转发

proxy:{
    '/api':{
      target:'http://localhost:8080/',//目标服务器地址
      changeOrigin:true, //开启代码里服务进行转发
      pathRewrite:{ //进行路径重写
        '^/api':'' //重写路径
      }
    }
  }

在把中间代理加入到test.js

 getList(){
        const promise1 = myaxios({
            method:'get',
            url:'/api/data.json'
        })
        return promise1
    }

修改后重启项目

image.png 到此为止跨域的问题就解决了