我在下面的链接中添加了过滤器作为问题的答案
Spring Boot Data Rest + CORS not being enabled properly for OPTIONS/DELETE
我的修改后的代码是:
import java.io.IOException;
import java.util.regex.Pattern;
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.apache.log4j.Logger;
import org.thymeleaf.util.StringUtils;
public class CorsFilterUtil implements Filter {
final Logger LOGGER = Logger.getLogger(CorsFilterUtil.class);
private static final Pattern PATTERN = Pattern.compile("^[a-zA-Z0-9 ,-_]*$");
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String origin;
String credentialFlag;
if (request.getHeader("Origin") == null) {
origin = "*";
credentialFlag = "false";
} else {
origin = request.getHeader("Origin");
credentialFlag = "true";
}
// need to do origin.toString() to avoid findbugs error about response splitting
response.addHeader("Access-Control-Allow-Origin", origin.toString());
response.setHeader("Access-Control-Allow-Credentials", credentialFlag);
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+request.getMethod()+"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
if ("OPTIONS".equals(request.getMethod())) {
LOGGER.info("Received OPTIONS request from origin:" + request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS,PUT,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
String headers = StringUtils.trim(request.getHeader("Access-Control-Request-Headers"));
if (!PATTERN.matcher(headers).matches()) {
throw new ServletException("Invalid value provided for 'Access-Control-Request-Headers' header");
}
response.setHeader("Access-Control-Allow-Headers", headers); // allow any headers
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) {
// Do nothing
}
@Override
public void destroy() {
// Do nothing
}
}
我已经尝试了doFilter以及2种情况。
chain.doFilter(req, res);
chain.doFilter(request, response);
但我对OPTIONS获得了同样的效果。
请让我知道我应该添加什么来工作。
答案 0 :(得分:0)
您可以创建一个类来配置CORS选项。以下是将所有映射添加到Cors注册表的示例配置。您将根据自己的需求进行调整。 您可以在https://spring.io/guides/gs/rest-service-cors/网页上查看带有说明的示例。
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
.allowedOrigins("*")
.allowedHeaders("*");
}
}