問題
在頁面上要使用 Ajax 請求去擷取另外一個服務的資料,由于浏覽器的 同源政策,是以直接請求會得到一個 Error。
Failed to load https://www.baidu.com/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
大概就是這樣的一個錯誤,關鍵詞是 Access-Control-Allow-Origin,一般出現這個都是跨域問題。
解決方案
解決跨域問題的方式有很多,但這裡之說 Cors 的方案。
在背景添加一個 Filter 過濾器
public class CustomCorsFilterConfig implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//允許所有來源
String allowOrigin = "*";
//允許以下請求方法
String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
//允許以下請求頭
String allowHeaders = "Content-Type,X-Token,Authorization";
//允許有認證資訊(cookie)
String allowCredentials = "true";
String origin = request.getHeader("Origin");
//此處是為了相容需要認證資訊(cookie)的時候不能設定為 * 的問題
response.setHeader("Access-Control-Allow-Origin", origin == null ? allowOrigin : origin);
response.setHeader("Access-Control-Allow-Methods", allowMethods);
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
//處理 OPTIONS 的請求
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
在 web.xml 檔案中添加攔截器配置(注:如果可能就配置成第一個 Filter)
customCorsFilterConfig
CustomCorsFilterConfig
customCorsFilterConfig
credentials: 'include',
})
.then(res => res.json())
.then(json => console.log(json))
注:如果想要服務端傳回 Set-Cookie(SessionId 也需要通過這個響應屬性去設定) 就必須設定這個請求參數!
那麼,之後在前端跨域請求的時候就可以愉快地玩耍啦(v^_^)v
以上就是Java 跨域問題的處理方式的詳細内容,更多關于Java 跨域的資料請關注聚米學院其它相關文章!