概念

跨域:浏览器对javascript的同源策略的限制,同源策略/SOP(Same origin policy)是一种约定,由Netscape公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS、CSRF等攻击。所谓的同源是指,域名、协议、端口均为相同。,即便两个不同的域名指向同一个ip地址,也非同源。

同源限制的行为有

  • Cookie、LocalStorage 和 IndexDB 无法读取
  • DOM 和 JS 对象无法获取
  • Ajax请求发送不出去

如下报错,即为跨域问题
在这里插入图片描述

跨域的原因

跨域原因示例
域名不同www.jd.com与www.taobao.com
域名相同,端口不同www.jd.com:8080与www.jd.com:8081
二级域名不同item.jd.com与miaosha.jd.com

http和https也属于跨域

为什么会有跨域问题

跨域不一定出现跨域问题,一个页面发起的ajax请求,只能是与当前页域名相同的路径,这能有效的组织跨站攻击

跨域问题的解决方案

前端

  • Jsonp
<script>
var script = document.createElement('script');
script.type = 'text/javascript';

// 传参并指定回调执行函数为onBack
script.src = 'http://www.....:8080/login?user=admin&callback=onBack';
document.head.appendChild(script);

// 回调执行函数
function onBack(res) {
    alert(JSON.stringify(res));
}
</script>

后端

  • CORS

增加配置类 TestCorsConfiguration.java

package com.test.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class TestCorsConfiguration {

    @Bean
    public CorsFilter corsFilter(){
        //初始化配置对象
        CorsConfiguration configuration = new CorsConfiguration();
        //允许跨域的域名,如果要携带cookie,不能写*。*:代表所有域名都可以跨域访问

        configuration.addAllowedOrigin("http://manage.test.com");
        configuration.setAllowCredentials(true);//设置是否允许携带cookie
        configuration.addAllowedMethod("*");//代表所有的请求方法
        configuration.addAllowedHeader("*");//允许携带所有头信息


        //初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource =new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",configuration);
        //返回实例,参数cors配置源对象
        return new CorsFilter(configurationSource);
    }
}

运维

  • nginx反向代理

因为比较简单,这里就不展示Nginx的解决方案了

小结

跨域未必会出现跨域问题,跨域的解决方案有很多,后端和前端都可以,我比较喜欢从后端解决这个问题呢,除了以上列出的方案还有其他的解决办法,一个问题有很多解决办法,从中找最优解吧。
在这里插入图片描述

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐