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

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

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

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);
                });
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值