非简单请求中POST请求的Options预请求403异常的跨域处理

  • Post author:
  • Post category:其他


 在http请求中,post请求的数据在请求体中,在spring MVC中通过@RequestBody接收。
 post请求属于http请求中的复杂请求,http协议在浏览器中对复杂请求会先发起一次Options的预请求,发起Options请求常会报403错误:
   Failed to load https://one.xxx.com/abd : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://other.xxxx.com' is therefore not allowed access. The response had HTTP status code 403.
   针对这种情况,通常是在DispacerServlet中没有找都到执行Options请求的方法。在做跨域处理时,通常配置好跨域请求头信息后,常常忽略在spring MVC中添加对Options请求的处理。
   解决办法有三种:
   1. 在Filter中添加对Options请求的支持处理
   public class TokenFilter implements Filter {

		@Value("${redirect.login.page.url}")
		private String loginPageUrl;
	
		@Override
		public void init(FilterConfig filterConfig) throws ServletException {
		}

		@Override
		public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
				throws IOException, ServletException {
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) resp;
			**setCorsFilter(request, response);**   // 设置跨域响应头
			
			String method = ((HttpServletRequest) request).getMethod();
			**if (method.equals("OPTIONS")) {
				response.setStatus(HttpServletResponse



版权声明:本文为qq_36956015原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。