【SpringBoot】解决前后端分离的跨域‘Access-Control-Allow-Origin‘ header in the response must not be the wildcard
程序员文章站
2022-03-07 11:45:42
index.html#/index:1 Access to XMLHttpRequest at ‘http://127.0.0.1:8083/product/list?pageSize=20’ from origin ‘http://localhost:8083’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access....
index.html#/index:1 Access to XMLHttpRequest at ‘http://127.0.0.1:8083/product/list?pageSize=20’ from origin ‘http://localhost:8083’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
效果图
过滤器
package com.bennyrhys.mall.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 处理跨域的过滤器
*/
public class CrosFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
//*号表示对所有请求都允许跨域访问
res.addHeader("Access-Control-Allow-Origin", "*");
// res.addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// res.addHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(servletRequest, servletResponse);
}
// https://blog.csdn.net/df1445/article/details/104723298/?utm_medium=distribute.pc_relevant_bbs_down.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_bbs_down.none-task-blog-baidujs-1.nonecase
@Override
public void destroy() {
}
}
启动类
/**
* 配置跨域访问的过滤器
* @return
*/
@Bean
public FilterRegistrationBean registerFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.addUrlPatterns("/*");
bean.setFilter(new CrosFilter());
return bean;
}
注意:往往是访问的localhost != 127.0.0.1导致的跨域不一致
本文地址:https://blog.csdn.net/weixin_43469680/article/details/110812743
上一篇: HTML如何设置video为不透明背景
下一篇: 了解NodeJS中的可读流