利用nginx解决跨域问题

Access to XMLHttpRequest at 'http://xxxx/api/getRouters' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

发送请求的时候浏览器突然报出这个错误,正常一看原因应该是后台的cors配置有问题,但是后台那边配置了好久还是报这个错误,很诡异,然后想着在开发环境下由我这个前端来解决问题,尝试了一下webpack里面的devserver设置代理,发现怎么都不成功,之前没尝试过,反正就是有问题,最后在我电脑上装了一个nginx设置下反向代理解决了这个问题。
首先前端电脑装下nginx更改下配置文件nginx.conf

     server {
        listen       80;
        server_name 127.0.0.1 localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /Applications/MxSrvs/www; #这个是目录不用管它
            index  index.html index.htm index.php;
            proxy_pass http://localhost:8080/; #这里填写你dev环境的IP和端口
        }
         location /api/ {
            proxy_pass http://192.168.43.125:51102/;  #这里填写你要反向代理的api
        }
       }

前端用nginx反向代理的原理是,我现在用nginx把的dev服务器全部通过nginx自己启动的服务去代理访问,然后我又在nginx把你的远程接口地址再转发到/api/这个目录 然后我直接用localhost就OK了,这时候端口,协议,域名一直,解决跨域。
但是如果这么做得话 前台会一直报热更新的错误,这里把热加载关了即可
解决方案
注释掉

node_modules\sockjs-client\dist\sockjs.js

里面
1604行这个就可以了

 try {
    // self.xhr.send(payload);
  } catch (e) {
    self.emit('finish', 0, '');
    self._cleanup(false);
  }

利用devserve去解决开发环境下的跨域问题

module.exports = {   
devServer:{
    host: 'localhost',//target host
    port: 8080,
    //proxy:{'/api':{}},代理器中设置/api,项目中请求路径为/api的替换为target
    proxy:{
        '/api':{
            target: 'http://192.168.1.1:8888',//代理地址,这里设置的地址会代替axios中设置的baseURL
            changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
            //ws: true, // proxy websockets
            //pathRewrite方法重写url
            pathRewrite: {
                '^/api': '/' 
                //pathRewrite: {'^/api': '/'} 重写之后url为 http://192.168.1.88:9999/xxxx
                //pathRewrite: {'^/api': '/api'} 重写之后url为 http://192.168.1.88:9999/api/xxxx
           }
    }}
},
//...
}
Last modification:February 5, 2020
If you think my article is useful to you, please feel free to appreciate