• SpringBoot跨域问题


     一、适用场景:


    HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,要比http协议安全。

    当我们对外提供服务是需要通过域名访问我们的服务,获取数据,在内网中我们可以通过http访问,前端访问后端也可以通过http,这时候的协议是一致的不会存在跨域问题。
     

    当前端提供的是https 后端提供的确实http,就会出现跨域问题。
    我们一般对外的服务都是通过https的,所以需要后端解决跨域访问问题。前端提供出去的域名一定是HTTPS协议。

    二、出现问题:

    访问接口:
    strict-origin-when-cross-origin

    访问服务:
    When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

    意思是:当allowCredentials为true时,allowingOrigins不能包含特殊值“ *”,因为无法在“ Access-Control-Allow-Origin”响应标头上设置。要允许凭据具有一组来源,请明确列出它们或考虑改用“ allowedOriginPatterns”。
     

    三、解决-两个类建议和启动类同级目录

    1. @SpringBootConfiguration
    2. public class MyWebConfigurer implements WebMvcConfigurer {
    3. @Override
    4. public void addCorsMappings(CorsRegistry corsRegistry) {
    5. /**
    6. * 所有请求都允许跨域,使用这种配置就不需要
    7. * 在interceptor中配置header了
    8. */
    9. corsRegistry.addMapping("/**")
    10. .allowCredentials(true)
    11. .allowedOriginPatterns("*")
    12. .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
    13. .allowedHeaders("*")
    14. .maxAge(3600);
    15. }
    16. }
    1. public class ProcessInterceptor implements HandlerInterceptor {
    2. @Override
    3. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    4. httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    5. httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    6. httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    7. httpServletResponse.setHeader("X-Powered-By", "Jetty");
    8. String method = httpServletRequest.getMethod();
    9. if (method.equals("OPTIONS")) {
    10. httpServletResponse.setStatus(200);
    11. return false;
    12. }
    13. System.out.println(method);
    14. return true;
    15. }
    16. @Override
    17. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    18. }
    19. @Override
    20. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    21. }
    22. }

    每天努力一点,每天都在进步

  • 相关阅读:
    32 道 Spring 常见面试总结(附详细参考答案),我经常拿来面试别人
    合成复用原则
    NFT协议OMNI因重入攻击损失1300ETH
    Kubernetes:(七)优化大法(江湖失传已久的武林秘籍)
    SiO2/PAA/Ag复合纳米粒/酞菁修饰磁性温敏二氧化硅纳米微球/中空SiO2/TiO2纳米微球的制备
    【机器学习】037_暂退法
    python+opencv+深度学习实现二维码识别 计算机竞赛
    Python - python如何连接sql server数据库
    java版本+工程项目管理系统源码+项目模块功能清单+spring cloud +spring boot
    Github上遇到的一些问题
  • 原文地址:https://blog.csdn.net/dingjianmin/article/details/134050951