Spring Boot Access-Control-Allow-Origin [重复]
Posted
技术标签:
【中文标题】Spring Boot Access-Control-Allow-Origin [重复]【英文标题】:Spring boot Access-Control-Allow-Origin [duplicate] 【发布时间】:2020-05-27 21:08:57 【问题描述】:当我尝试使用我的 Angular 客户端调用我的后端时遇到问题 我在 post、put 和 delete 方法中总是有这个错误:
Access to XMLHttpRequest at 'http://localhost:8087/categories' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
这是我的后台
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type,Access-Control-Request-Method, Access-Control-Request-Headers, credential, X-XSRF-TOKEN, authorization");
response.setHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, authorization");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
response.setHeader("Access-Control-Allow-Credentials", "true");
if (request.getMethod().equals("OPTIONS"))
response.setStatus(HttpServletResponse.SC_OK);
我现在不明白为什么我的客户被屏蔽了
【问题讨论】:
【参考方案1】:以下是我使用Angular8-springboot 应用程序的方法。
我将控制器标记为:@CrossOrigin(origins = "http://localhost:4200")
这是我的 Cors 配置类。
@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, 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()
【讨论】:
以上是关于Spring Boot Access-Control-Allow-Origin [重复]的主要内容,如果未能解决你的问题,请参考以下文章
为啥 Spring Boot 应用程序 pom 同时需要 spring-boot-starter-parent 和 spring-boot-starter-web?
《02.Spring Boot连载:Spring Boot实战.Spring Boot核心原理剖析》