• Requests blocked by CORS policy in spring boot and angular


    在本地启动Spring Boot后端和Angular前端调试时遇到跨域访问的问题导致前端请求失败。

    错误描述

    Access to XMLHttpRequest at 'http://localhost:8080/...' from origin 'http://localhost:4201' 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.

    解决方案

    添加一个Filter使后端支持跨域访问,Spring Boot会自动扫描Filter,无需手动添加。

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    
    @Component
    public class SimpleCORSFilter implements Filter {
    
        private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
    
        public SimpleCORSFilter() {
            log.info("SimpleCORSFilter init");
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
    
            chain.doFilter(req, res);
        }
    
        @Override
        public void init(FilterConfig filterConfig) {
        }
    
        @Override
        public void destroy() {
        }
    
    }

    参考:https://stackoverflow.com/questions/32319396/cors-with-spring-boot-and-angularjs-not-working

    转载请注明出处:https://www.cnblogs.com/keitsi/p/10594758.html

  • 相关阅读:
    干掉idea视图黄色警告
    idea插件 Background Image Plus 随机更换背景图片
    es的rest风格的api文档
    使用postman对elasticsearch接口调用
    es插件安装
    emoji表情等特殊字符处理和存储的两个方案
    java8两个字段进行排序问题
    java 必应壁纸批量下载
    elasticsearch学习(1)
    RocketMq报错 Java HotSpot(TM) Server VM warning:
  • 原文地址:https://www.cnblogs.com/keitsi/p/10594758.html
Copyright © 2020-2023  润新知