spring boot 拦截器解决跨域问题

拦截器解决跨域问题

  • spring boot
    • 前后端分离多次跨域
    • 源码

spring boot

		//*表示允许所有域名跨域
		response.addHeader("Access-Control-Allow-Origin", "*");
		//允许跨域的Http方法
		response.addHeader("Access-Control-Allow-Methods", 			 "GET,POST,PUT,DELETE");
		//头部
		response.addHeader("Access-Control-Allow-Headers", "content-type, Authorization, currentUserToken");
		//头部
		response.addHeader("Access-Control-Request-Headers", 
				"Origin, X-Requested-With, content-Type, Accept, Authorization, currentUserToken");

前后端分离多次跨域

	//前段发起一个请求,后端收到两个请求,一个方法为: OPTIONS     第二个真实的请求
	if (request.getMethod().equals("OPTIONS")) {
		return true;
	}
		

源码

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class CrosIntercetpor implements HandlerInterceptor {
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	@Value("${system.jwt.token.max-age}")
	private long tokenMaxAge;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("---------------");
		Enumeration<?> enum1 = request.getHeaderNames();
        while (enum1.hasMoreElements()) {
            String key = (String) enum1.nextElement();
            String value = request.getHeader(key);
            System.out.println(key + "\t" + value);
        }
		System.out.println("***************");
		
		//前段发起一个请求,后端收到两个请求,一个方法为: OPTIONS     第二个真实的请求
		if (request.getMethod().equals("OPTIONS")) {
			return true;
		}
		
		//*表示允许所有域名跨域
		response.addHeader("Access-Control-Allow-Origin", "*");
		//允许跨域的Http方法
		response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
		//头部
		response.addHeader("Access-Control-Allow-Headers", "content-type, Authorization, currentUserToken");
//		//头部
		response.addHeader("Access-Control-Request-Headers", 
				"Origin, X-Requested-With, content-Type, Accept, Authorization, currentUserToken");
		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 {
	}

}

参考地址

你可能感兴趣的:(java)