这里是文章模块栏目内容页
Vue配置proxyTable代理解决axios跨域访问错误

Vue配置proxyTable代理解决axios跨域访问错误

在js前端跨域问题,在开发vue项目时,本地调试经常遇到。Vue项目本地一般运行在localhost:8080端口;

而请求的api接口通常部署在其他域名或者localhost的其他端口上,例如localhost:841端口。

  mounted(){
      axios.get("http://localhost:841/index/index.php?isapi=1")
      .then(response=>{
          this.site = response;
          console.log('请求站点数据', response);
      })
  },

这个时候,在vue里面用axios发起get、post请求,都被浏览器提示一下错误:

Access to XMLHttpRequest at ' 
 from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
  header is present on the requested resource.


解决这个问题有两种办法:

1、前端方式,采用代理模式(前提是后端的代码,没有设置过限制域名访问);

2、后端方式,让后端代码正在接口的返回数据头部,即header加入Access-Control-Allow-Origin 的值为 “*”;


下面主要采用方法1,通过配置vue的配置文件,加入对proxyTable 参数的设置,配置一个代理;

找到config.index.js 

proxyTable: {
     
      '/api': {
        target:'http://localhost:841/', // 你请求的第三方接口
        changeOrigin:true,   /*在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,
  这样服务端和服务端进行数据的交互就不会有跨域问题*/
        pathRewrite:{  // 路径重写,
          '^/api': ''  /* 替换target中的请求地址,也就是说/api=/target,
          请求target这个地址的时候直接写成/api即可。*/
        }
      }
    },

然后找到webpack-dev-server 服务器配置文件webpack.dev.conf.js 

正在devServer 参数里面有 proxy 这个参数;

把它 设置为 config.dev.proxyTable;

如果你的webpack.dev.conf.js 没有引入config.index.js。

可以直接把proxyTable 这个对象,配置webpack-dev-server 的配置文件里的 proxy参数上。


然后 在需要axios 请求的业务.Vue 内容:

  mounted(){
      axios.get("/api/index/index.php?isapi=1")
      .then(response=>{
          this.site = response;
          console.log('请求站点数据', response);
      })
  },

大功告成,能正常的放回接口数据。代理设置成功。