nginx /Java 解決跨域問題方案

简单的李發表於2024-06-05
 location / {
        #if ($request_method = 'OPTIONS') {
           # add_header 'Access-Control-Allow-Origin' '*';
           # add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

            #add_header 'Access-Control-Allow-Headers' '*';

           # add_header 'Access-Control-Max-Age' 1728000;
           # add_header 'Content-Type' 'text/plain charset=UTF-8';
           # add_header 'Content-Length' 0;
           # return 204;
        #}
        #if ($request_method = 'POST') {
          #  add_header 'Access-Control-Allow-Origin' '*';
         #   add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
          #  add_header 'Access-Control-Allow-Headers' '*';
        #}
       # if ($request_method = 'GET') {
       #     add_header 'Access-Control-Allow-Origin' '*';
       #     add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
       #     add_header 'Access-Control-Allow-Headers' '*';
       # }
        proxy_pass http://localhost:8085;
        proxy_set_header Host  $host:2385;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        
      }
    }

Java 解決方案

   String method = request.getMethod();
        if ("options".equalsIgnoreCase(method)) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Max-Age", "1728000");
            response.setHeader("Content-Type", "text/plain charset=UTF-8");
            response.setHeader("Content-Length", "0");
            response.getOutputStream().close();
            return true;
        } else {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "*");
            return false;
        }
    }

在專案開發過程中,多個子系統之間的功能互動,前端出現跨域請求解決方案,前端VUE,後端Java(非springMVC架構)經過測試執行,上述兩種方案都可以解決當前需求,當然也存在不同點

1.nginx代理的子系統都需要配置nginx.conf,需要運維支援,不夠安全

2.Java方案有一個問題是跨域介面必須單獨使用,不然會出現非跨域請求設定跨域介面,無法獲取有效資料問題,目前還沒有找到問題所在。所以跨域介面必須與非跨域介面單獨分開,好處安全問題不用擔心

以上是個人經歷,不夠深入,獨家之言,難免偏頗,有錯誤之處,請留言更正

相關文章