老白的释然 发表于 2019-1-28 13:50:11

nginx解决vuejs与springboot跨域问题

本帖最后由 老白的释然 于 2019-1-28 13:55 编辑

问题在实施前后端分离的时候,vuejs与springboot通常不在同一台服务器,这个时候,vuejs调用springboot的时候通常会出现跨域问题。
解决思路这里的解决方案,主要是通过nginx搭建一个静态文件服务器,然后,再在此基础上面启用nginx的反向代理功能,反向代理springboot的rest接口服务即可。
nginx.conf# 启动多worker进程
worker_processesauto;
events {
    worker_connections1024;
}
http {
    include       mime.types;
      # 假装配置springboot服务集群
      upstream myspringboot {
      server 127.0.0.1:8081;
    }
    default_typeapplication/octet-stream;
    # 日志格式
    log_formatmain'$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    sendfile      on;
    keepalive_timeout65;
    # 启用gzip压缩
    gzipon;
    server {
      # nginx服务器对外8080端口
      listen       8080;
      server_namelocalhost;
      # 日志输出
      access_loglogs/myvuejs.access.logmain;
      # vuejs静态文件配置
      location / {
            root myvuejs;
            indexindex.html index.htm;
      }
      # 反向代理springboot接口服务
      location /api/springboot/ {
                        # 解决springboot中获取远程ip的问题
                        proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://myspringboot/api/springboot/;
      }
      error_page   500 502 503 504/50x.html;
      location = /50x.html {
            root   html;
      }
    }
}其中:root myvuejs;表示myvuejs文件夹里面的全部都是vuejs的配置文件;反向代理的部分,主要就是将前端调用的/api/springboot/的rest接口请求,反向代理到http://xxxxxxxx:8081/api/springboot/的springboot接口上面去。**注意:**在Spring boot获取ip地址需要使用HttpServletRequest request.getHeader("X_FORWARDED_FOR");方法

总结跨域问题,无需在springboot或vuejs打开跨域支持,直接使用nginx的静态文件服务器和反向代理服务器功能就可以解决这个问题了。

页: [1]
查看完整版本: nginx解决vuejs与springboot跨域问题