制作一个拦截器,在返回体中添加 响应头允许次次跨域
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); //允许跨域请求
以下是我的完整代码:
我的完整代码:
@Component //通过拦截器实现跨域请求
@Slf4j
public class AllInterceptorimplements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
// System.out.println("拦截器执行");
request.setCharacterEncoding("UTF-8"); //设置请求编码
log.info("添加跨域支持:" + request.getRequestURL().toString());
log.info("请求方法为 ===" + request.getMethod());
//如果是OPTIONS 请求 ,就设置允许该次请求
if (request.getMethod().equals("OPTIONS")) {
log.info("设置允许该请求");
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); //允许跨域请求
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
response.setHeader("Access-Control-Request-Method", "GET,POST,PUT,DELETE"); //返回允许的方法
response.setHeader("Access-Control-Allow-Credentials", "true"); //允许携带Cookie
response.setCharacterEncoding("UTF-8"); //设置响应编码
log.info("OPTIONS请求直接返回");
return false;
}
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); //允许跨域请求 response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild"); response.setHeader("Access-Control-Request-Method", "GET,POST,PUT,DELETE"); //返回允许的方法 response.setHeader("Access-Control-Allow-Credentials", "true"); //允许携带Cookie
response.setCharacterEncoding("UTF-8"); //设置响应编码
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
}
}