方案解决一:
实现 WebMvcConfigurer 接口,请勿实现WebMvcConfigurerAdapter 接口,因为在 spring5.0中, WebMvcConfigurerAdapter 以被废除
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
方案解决二:
- Access-Control-Allow-Origin:必填字段, "*" 表示接受任意域名的请求
- Access-Control-Allow-Methods: 必填字段,它的值是逗号分隔的一个具体的字符串或者*,表明服务器支持的所有跨域请求的方法
- Access-Control-Allow-Credentials : 该字段可选。它的值是一个布尔值,表示是否允许发送Cookie,默认情况下,不发生Cookie,即:false
- Access-Control-Max-Age 该字段可选,用来指定本次预检请求的有效期,单位为秒。在有效期间,不用发出另一条预检请求,如果在开发中,发现每次发起请求都是两条,一次OPTIONS,一次正常请求,注意是每次,那么就需要配置Access-Control-Max-Age,避免每次都发出预检请求。
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
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);
}
}