(剧透)答案在最下面的补充
加一个拦截器,在需要跨域的请求头上添加CORS
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 跨域CORS拦截器
* @author Fcx
*/
@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", "*,token");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
return true;
}
}
需要注意:
- 在我们理解中,默认*号 代表允许所有的,但是有一些浏览器不能识别星号, 为了避免这种情况,自己所需要的请求头都手动加上, 比如上面我自己加的token 这块是个大坑~
- 跨域的情况用nginx处理是最好的,拦截器只是个备用方案
2019.6.10 补充解决不识别或者不允许星号的问题
/**
* 跨域CORS拦截器
*
* @author Fcx
*/
@Component
public class CorsInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getHeader(HttpHeaders.ORIGIN) != null) {
//添加跨域CORS
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token, enctype, *");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Max-Age", "3600 * 24");
}
return true;
}
}
从请求头里拿到当前的Origin,这样跟*的效果就一样啦,应该再也不会有跨域的问题了