解决No 'Access-Control-Allow-Origin' header is present on the requested resource.跨域问题

时间:2022-08-28 15:06:24

跨域错误


 

错误原因


 

解决方法
在后台写一个过滤器过滤器来改写请求头头

CorsFilter.java

public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;

String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
String method = request.getMethod();
if(method.equalsIgnoreCase("OPTIONS")){
servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
}else{
filterChain.doFilter(servletRequest, servletResponse);
}
}

@Override
public void destroy() {

}
}
备注:

在web.xml文件中添加代码

<filter>
<filter-name>corsFilter</filter-name>
<filter-class>xxx.xxx.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 
---------------------
作者:汤姆猫丶
来源:CSDN
原文:https://blog.csdn.net/qq_39403545/article/details/82116121
版权声明:本文为博主原创文章,转载请附上博文链接!