java与前端对接,跨域问题
// 最简单的处理方式 response.setHeader("Access-Control-Allow-Origin","*");
2.
// 这个可以用过滤器统一处理 if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { // CORS "pre-flight" request response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); response.addHeader("Access-Control-Max-Age", "1800");//30 min }
3.使用拦截器统一做跨域处理
@Component public class CORSInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //添加跨域CORS response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); return true; } }
4.最后启用拦截器就ok,以下展示在Spring-boot配置
public class WebConfigTest extends WebMvcConfigurerAdapter { @Autowired private CORSInterceptor corsInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(corsInterceptor); } }