跨域問題解決方案
今天在寫一個項目的時候出現了一個很莫名其妙的問題,除了Get請求其他的請求都報錯
在使用Post請求的時候,總是報以下錯誤。
原因是因爲 header中存在自定義屬性(content-type)
錯誤原因:
前端設置: credentials: ‘include’,( 允許 cookie 共享,跨域問題,傳Cookie是必須配置)
不傳遞Cookie時,不允許配置credentials
在正式跨域的請求前,瀏覽器會根據需要,發起一個“PreFlight”(也就是Option請求),用來讓服務端返回允許的方法(如get、post),被跨域訪問的Origin(來源,或者域),還有是否需要Credentials(認證信息)
如果跨域的請求是Simple Request(簡單請求 ),則不會觸發“PreFlight”。Mozilla對於簡單請求的要求是:
以下三項必須都成立:
- 只能是Get、Head、Post方法
- 除了瀏覽器自己在Http頭上加的信息(如Connection、User-Agent),開發者只能加這幾個:Accept、Accept-Language、Content-Type、。。。。
- Content-Type只能取這幾個值:
application/x-www-form-urlencoded
multipart/form-data
text/plain
解決方案:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String origin = request.getHeader(HttpHeaders.ORIGIN);
log.info("origin is :" + origin);
// 添加跨域CORS
if (!StringUtils.isEmpty(origin) && isDomainAllowed(origin)) {
response.setHeader("Access-Control-Allow-Methods", "OPTIONS,HEAD,DELETE,PUT,POST,PATCH,GET,TRACE,*");
response.setHeader("Access-Control-Allow-Headers", "content-type,*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin", origin);
}
return true;
}