美文网首页
前后端分离跨域解决方案(反向代理)

前后端分离跨域解决方案(反向代理)

作者: 路人甲Boger | 来源:发表于2020-05-08 16:55 被阅读0次

    前后端分离是大趋势,今天就前后端分离中出现的跨域参考各大博文,实现下通过服务器反向代理解决跨域问题的一个例子,小小的卖弄一下。大神勿喷,请多指教!!

    先说下思路吧,开发中碰到的跨域提示是这样的

    XMLHttpRequest cannot load http://www.test1.com/jqWebPrj/getCountAndTotalMil?driverNo=37.
    No 'Access-Control-Allow-Origin' header is present on the requested resource. 
    Origin 'http://www.test2.com' is therefore not allowed access.
    
    vue.$http.get(' http://www.test1.com/getCountAndTotalMil?driverNo=37')
                    .then((response) => {
                        var count = response.data;
                        vue.items.push(count);
                    }, (response) => {
                        console.dir(response);
                    });
    

    出现如上提示是由于我在 www.test2.com 的项目上通过Ajax请求 www.test1.com上的资源,提示资源无法访问。

    www.test1.com是后台程序服务器。
    www.test2.com是前端项目服务器。

    解决思路是
    让前段通过访问test2的网址能够访问到test1的资源,说的有点不明白。。。

    1. 在test2规定访问后台RUI特定格式例如 www.test2.com/api/......
    2. 前台服务器通过配置nginx把有 api 标记的资源请求转发到www.test1.com 服务器上

    这样前端依旧访问自己的网址请求资源就不会出现跨域的问题。

    nginx配置如下

    www.test2.com 的请求中带有 /api 的资源转发到 www.test1.com 上,其他请求不转发依旧访问自己的资源

    
        server {
            listen       80;
            server_name  www.test2.com;
            #charset koi8-r;
            #access_log  logs/host.access.log  main;
            location / {
                root   html;
                index  index.html index.htm;
                #client_max_body_size    1000m; 
            }
            location /api/ {
                proxy_pass   http://www.test1.com/;  
                #client_max_body_size    1000m; 
            }
            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                root   html;
            }
        }
    

    Ajax改成这样

    vue.$http.get(' http://www.test2.com/api/getCountAndTotalMil?driverNo=37')
                    .then((response) => {
                        var count = response.data;
                        vue.items.push(count);
                    }, (response) => {
                        console.dir(response);
                    });
    

    相关文章

      网友评论

          本文标题:前后端分离跨域解决方案(反向代理)

          本文链接:https://www.haomeiwen.com/subject/cytqnhtx.html