欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【SpringBoot】解决前后端分离的跨域‘Access-Control-Allow-Origin‘ header in the response must not be the wildcard

程序员文章站 2022-06-17 10:15:05
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.

效果图

【SpringBoot】解决前后端分离的跨域‘Access-Control-Allow-Origin‘ header in the response must not be the wildcard
【SpringBoot】解决前后端分离的跨域‘Access-Control-Allow-Origin‘ header in the response must not be the wildcard

过滤器

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

相关标签: # SpringBoot