问题
在页面上要使用 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 跨域的资料请关注考高分网其它相关文章!



