@Configuration
public class CorsConfigure implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
@Component
public class CorsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "86400");
response.setHeader("Access-Control-Allow-Headers", "*");
// 如果是 OPTIONS 则结束请求
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
response.setStatus(HttpStatus.NO_CONTENT.value());
return false;
}
return true;
}
}
1
treblex 2020-09-07 18:05:48 +08:00
allowCredentials 为 true 的时候需要具体域名,不能使用*匹配,看下是不是这个
|
2
treblex 2020-09-07 18:07:40 +08:00
@suke971219 #1 options 请求应该返回 204 的
|
3
liubx OP @suke971219 谢谢。
现在找到原因了。是 shiro 把 options 拦截了。因为 options 没有挟带 cookie 。现在让 shiro 不拦截 options 就好了 |