• 关于出现2次 Access-Control-Allow-Origin:* 导致跨域失败


    1.在代码端(Spring boot)增加以下跨域代码

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebFilter(filterName = "CorsFilter ")
    @Configuration
    public class CorsFilter implements Filter {
        @Autowired
        private Environment env; 
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            //允许跨域的域名列表,多个用逗号隔开
            String alloworigin = env.getProperty("alloworigin");
            //是否允许带cookie内容
            String allowCredentials = env.getProperty("allowCredentials");
    
            response.setHeader("Access-Control-Allow-Origin",alloworigin);
            //注意:要把 Access-Control-Allow-Credentials 设置为 False,否则本地开发调试会发生跨域
            response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTION");
            response.setHeader("Access-Control-Max-Age", "3600");
            //response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, username, usertoken, lan_ip, net_ip, wxapitoken");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Cache-Control,Pragma,Content-Type,Token, username, usertoken ");
            response.setHeader("Access-Control-Expose-Headers", "username, usertoken ");
    
            String method = request.getMethod();
            if (method.equalsIgnoreCase("OPTIONS")) {
                res.getOutputStream().write("Success".getBytes("utf-8"));
            } else {
                chain.doFilter(req, res);
            }
        }
    }

    2.在Ngnix或Tomcat的配置中不要再设置 Access-Control-Allow-Origin:* 

       tomcat是在 conf/web.xml 文件里配置的,全文搜索 Origin 即可找到,如果有设置需要屏蔽;

  • 相关阅读:
    vue3自定义指令过滤input的输入内容
    我的收藏周刊011
    我的收藏周刊012
    20192416《系统与网络攻防技术》实验八实验报告
    Dapr学习(3)之服务调用概述
    摄影后期调色RAW数码照片图像HDR全景制作Lightroom(Lr)2022(Mac/win)
    新入手的苹果电脑需要安装的几款工具
    图片编辑工具Photoshop 2022中文
    Xmind 2022激活版终于等到你!
    矢量图像绘图设计(AI 2022)Illustrator 2022中文
  • 原文地址:https://www.cnblogs.com/lpq21314/p/15271969.html
Copyright © 2020-2023  润新知