最近在学习react.js,单页面应用,在进行跨站请求时,如果请求头中有其他参数,比如token之类,客户端(chrome)会先发送一个OPTIONS请求,后台需要支持这种请求,并返回202状态。
为了方便起见,暂时使用Filter来实现此功能。
Filter类代码如下:
public class CORSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Access-Control-Allow-Origin", "*"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // 响应类型允许的方法 httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE"); // 响应头设置 httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); if (httpRequest.getMethod().equals("OPTIONS")) { System.out.println("Filter 过滤器 执行 了 OPTIONS"); httpResponse.setStatus(202); //.setStatus(HttpStatus.NO_CONTENT); return; } chain.doFilter(request, response); } @Override public void destroy() { } }
这个Access-Control-Allow-Headers有什么用的?不知道。。。我太难了。。
原文地址:https://www.cnblogs.com/myjhaha/p/11721274.html
时间: 2024-11-10 03:59:32