(劇透)答案在最下面的補(bǔ)充
加一個(gè)攔截器,在需要跨域的請(qǐng)求頭上添加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;
}
}
需要注意:
- 在我們理解中,默認(rèn)*號(hào) 代表允許所有的,但是有一些瀏覽器不能識(shí)別星號(hào), 為了避免這種情況,自己所需要的請(qǐng)求頭都手動(dòng)加上, 比如上面我自己加的token 這塊是個(gè)大坑~
- 跨域的情況用nginx處理是最好的,攔截器只是個(gè)備用方案
2019.6.10 補(bǔ)充解決不識(shí)別或者不允許星號(hào)的問(wèn)題
/**
* 跨域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;
}
}
從請(qǐng)求頭里拿到當(dāng)前的Origin咒唆,這樣跟*的效果就一樣啦届垫,應(yīng)該再也不會(huì)有跨域的問(wèn)題了