Spring boot Access-Control-Allow-Origin 問題解決


Spring boot Access-Control-Allow-Origin 問題解決


最近在做一個項目,前后端分離,后端使用的框架是Spring boot,后端接口在使用swagger測試接口時沒有問題,前端調用接口時,控制台發生關於“Access-Control-Allow-Origin” 的報錯

Failed to load http://192.168.*.*:8888/system/list?page=0&size=999: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://192.168.*.*:8089' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

相關知識點

什么是跨域?

1、當兩個域具有相同的協議(如http), 相同的端口(如80),相同的host(如www.google.com),那么我們就可以認為它們是相同的域(協議,域名,端口都必須相同)。
2、跨域就指着協議,域名,端口不一致,出於安全考慮,跨域的資源之間是無法交互的(例如一般情況跨域的JavaScript無法交互,當然有很多解決跨域的方案)

Access-Control-Allow-Origin

Access-Control-Allow-Origin是HTML5中定義的一種解決資源跨域的策略。

他是通過服務器端返回帶有Access-Control-Allow-Origin標識的Response header,用來解決資源的跨域權限問題。

在Spring boot中的解決方式

在Spring boot中通常是可以通過增加過濾器,對返回響應中的請求頭增加相關配置,具體代碼如下:

/**
 * @Auther: yujuan 過濾器 解決跨域問題
 * @Date: 19-3-25 17:39
 * @Description:
 */
@Component
public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        HttpServletRequest reqs = (HttpServletRequest) req;

        // response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM