zoukankan      html  css  js  c++  java
  • 跨域问题解决

    一、跨域的由来

    为了保证用户信息的安全,防止恶意的网站窃取数据,目前,所有浏览器都实行了同源策略,要求域名、协议、端口必须都相同才属于同源,只有同源才可以访问其他页面的对象,否则将受到以下限制:

    (1) Cookie、LocalStorage 和 IndexDB 无法读取。
    (2) DOM 无法获得。
    (3) AJAX 请求不能发送。

    二、微服务之后跨域问题更普遍存在

    在现在前后端分离,分布式服务、微服务化之后,我们将复杂的业务拆分成细小的服务组件,部署到不同的主机下,往往存在不同的域名。因此,跨域问题,就更普遍存在了。

    三、跨域问题解决方法--通过 CORS 实现跨域

    分布式项目中,添加配置类:GlobalCorsConfig

     1 package cn.itsource.hrm.config;
     2 
     3 import org.springframework.context.annotation.Bean;
     4 import org.springframework.context.annotation.Configuration;
     5 import org.springframework.web.cors.CorsConfiguration;
     6 import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
     7 import org.springframework.web.filter.CorsFilter;
     8 
     9 @Configuration
    10 public class GlobalCorsConfig {
    11     @Bean
    12     public CorsFilter corsFilter() {
    13         //1.添加CORS配置信息
    14         CorsConfiguration config = new CorsConfiguration();
    15         //1) 允许的域,不要写*,否则cookie就无法使用了
    16         config.addAllowedOrigin("http://127.0.0.1:6001");
    17         config.addAllowedOrigin("http://localhost:6001");
    18         config.addAllowedOrigin("http://localhost:6002");
    19         config.addAllowedOrigin("http://127.0.0.1:6002");
    20         config.addAllowedOrigin("http://localhost:6003");
    21         config.addAllowedOrigin("http://127.0.0.1:6003");
    22         //2) 是否发送Cookie信息
    23         config.setAllowCredentials(true);
    24         //3) 允许的请求方式
    25         config.addAllowedMethod("OPTIONS");
    26         config.addAllowedMethod("HEAD");
    27         config.addAllowedMethod("GET");
    28         config.addAllowedMethod("PUT");
    29         config.addAllowedMethod("POST");
    30         config.addAllowedMethod("DELETE");
    31         config.addAllowedMethod("PATCH");
    32         // 4)允许的头信息
    33         config.addAllowedHeader("*");
    34         //2.添加映射路径,我们拦截一切请求
    35         UrlBasedCorsConfigurationSource configSource = new
    36                 UrlBasedCorsConfigurationSource();
    37         configSource.registerCorsConfiguration("/**", config);
    38         //3.返回新的CorsFilter.
    39         return new CorsFilter(configSource);
    40     }
    41 }
  • 相关阅读:
    paste 合并文件
    split 分割文件
    cut 从文本中提取一段文字并输出
    tailf 跟踪日志文件
    tail 显示文件内容尾部
    给Linux系统新增加一块硬盘
    Centos7+httpd+fastcgi安装提示错误
    Redhat 7使用CentOS 7的Yum网络源
    windows7下cmd窗口使用ssh命令
    PHP set_error_handler() 函数
  • 原文地址:https://www.cnblogs.com/htq29study/p/12002292.html
Copyright © 2011-2022 走看看