nginx反向代理前端服务到后端解决跨域

在做web开发的时候,由于前后端分离,根据同源策略两个服务不是同一个端口或者不是同域名,会造成跨域请求,如下图

在这里插入图片描述

Access to XMLHttpRequest at ‘http://localhost:8888/api/login/auth’ from origin ‘http://localhost:9520’ 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.

意思是从http://localhost:9520 前端服务发起的请求到后端服务http://localhost:8888/api/login/auth 不能接受 No ‘Access-Control-Allow-Origin’ 不遵循同源策略

面对跨域一般有三种方式:1.前端jsonp、2.后端处理、3、服务器处理

这里就用到第三种服务器处理,我选择用nginx反向代理两个服务来实现他们在一个服务器上面 这样就遵循了同源策略

nginx根目录->conf->nginx.config

这个是http{ }里面的server
server {
        listen       8888;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
		
		#代理前端nodejs项目
        location / {
                proxy_set_header X_Real_IP $remote_addr;
                proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_pass http://localhost:3000; #代理前端地址
                proxy_redirect off;
        }
		
		  #代理后台接口
          location /api/ {
              proxy_pass http://localhost:8080;    #转发请求的地址
              proxy_connect_timeout 6000;          #链接超时设置
              proxy_read_timeout 6000;             #访问接口超时设置
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
使用服务器处理的好处:在不改动前后端代码的情况下,便捷的处理请求,由于是代理了两端的服务依旧能够热部署(热更新)

注意事项: 反向代理后,前端的请求地址要改为http://localhost:8888/api/ (因为都在nginx的8888端口上,这个地址就是代理的后端请求地址,浏览器可以访问,http://localhost:8888则是被反向代理的前端地址),然后后端接口也要增加/api

比如原来请求是@RequestMapping("/login"),代理后改为@RequestMapping("/api/login"),如果后端springboot用了shiro等安全框架 里面的拦截地址也要改

nginx配置文件

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值