欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot項(xiàng)目中如何解決跨域問(wèn)題的最新方案?

 更新時(shí)間:2025年03月22日 15:56:39   作者:清醒的人最荒唐  
跨域問(wèn)題是瀏覽器為了保護(hù)用戶(hù)的信息安全,實(shí)施了同源策略(Same-Origin Policy),即只允許頁(yè)面請(qǐng)求同源(相同協(xié)議、域名和端口)的資源,當(dāng) JavaScript 發(fā)起的請(qǐng)求跨越了同源策略,即請(qǐng)求的目標(biāo)與當(dāng)前頁(yè)面的域名、端口、協(xié)議不一致時(shí),瀏覽器會(huì)阻止請(qǐng)求的發(fā)送或接收

跨域問(wèn)題是瀏覽器為了保護(hù)用戶(hù)的信息安全,實(shí)施了同源策略(Same-Origin Policy),即只允許頁(yè)面請(qǐng)求同源(相同協(xié)議、域名和端口)的資源,當(dāng) JavaScript 發(fā)起的請(qǐng)求跨越了同源策略,即請(qǐng)求的目標(biāo)與當(dāng)前頁(yè)面的域名、端口、協(xié)議不一致時(shí),瀏覽器會(huì)阻止請(qǐng)求的發(fā)送或接收。

一、同源策略

同源,就是咱們域名、端口號(hào)、ip、采用的協(xié)議都相同,那么我們就是同源的
反之就是不同源的?。。?br />出于瀏覽器的同源策略限制。同源策略(Sameoriginpolicy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會(huì)受到影響??梢哉f(shuō)Web是構(gòu)建在同源策略基礎(chǔ)之上的,瀏覽器只是針對(duì)同源策略的一種實(shí)現(xiàn)。
所以,用最簡(jiǎn)單的話來(lái)說(shuō),就是前端可以發(fā)請(qǐng)求給服務(wù)器,服務(wù)器也可以進(jìn)行響應(yīng),只是因?yàn)闉g覽器會(huì)對(duì)請(qǐng)求頭進(jìn)行判斷,所以要么前端設(shè)置請(qǐng)求頭,要么后端設(shè)置請(qǐng)求頭

一個(gè)域名地址由以下幾個(gè)部分組成:
http://www.aaa.com:8080/sie=UTF-8&wd=SpringBoot

    協(xié)議:http
    域名:子域名www,主域名aaa.com
    端口:8080

從一個(gè)域名的網(wǎng)頁(yè)去請(qǐng)求另一個(gè)域名的資源時(shí),協(xié)議,域名,端口任意不同,都會(huì)出現(xiàn)跨域問(wèn)題。
http://www.aaa.com:8080——>http://www.aaa.com:8080:同域訪問(wèn)
http://www.aaa.com:8080——>http://www.bbb.com:8080:跨域訪問(wèn)

二、跨域問(wèn)題

跨域報(bào)錯(cuò)如下:

Access to XMLHttpRequest at 'http://localhost:8080/t1' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
test1.html?_ijt=aekdfma33ut4n31cgsohdrjt89:17 {readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
jquery-1.9.1.min.js:5 GET http://localhost:8080/t1 net::ERR_FAILED 200

三、spring boot解決跨域問(wèn)題

對(duì)于 CORS的跨域請(qǐng)求,主要有以下幾種方式可供選擇:

  • 返回新的CorsFilter
  • 重寫(xiě) WebMvcConfigurer
  • 使用注解 @CrossOrigin
  • 手動(dòng)設(shè)置響應(yīng)頭 (HttpServletResponse)
  • 自定web filter 實(shí)現(xiàn)跨域

注意:

CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,對(duì)應(yīng)springBoot 1.3版本以上
上面前兩種方式屬于全局 CORS 配置,后兩種屬于局部 CORS配置。如果使用了局部跨域是會(huì)覆蓋全局跨域的規(guī)則,所以可以通過(guò) @CrossOrigin 注解來(lái)進(jìn)行細(xì)粒度更高的跨域資源控制。
其實(shí)無(wú)論哪種方案,最終目的都是修改響應(yīng)頭,向響應(yīng)頭中添加瀏覽器所要求的數(shù)據(jù),進(jìn)而實(shí)現(xiàn)跨域

1、使用CorsFilter

@Configuration
public class corsFilter {
    @Bean
    public CorsFilter CorsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);


        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

2、實(shí)現(xiàn)WebMvcConfigurer里面的addCorsMappings方法

@Configuration
public class corsFilter1 implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 匹配所有的路徑
                .allowCredentials(true) // 設(shè)置允許憑證
                .allowedHeaders("*")   // 設(shè)置請(qǐng)求頭
                .allowedMethods("GET","POST","PUT","DELETE") // 設(shè)置允許的方式
                .allowedOriginPatterns("*");
    }
}

3、@CrossOrigin局部跨域通過(guò)

@GetMapping("/t2")
@CrossOrigin
public Map t2() {
    HashMap<String, Object> map = new HashMap<>();
    User user = new User();
    user.setUsername("123456");
    user.setPassword("程世玉");
    map.put("user",user);

    return map;
}

4、添加響應(yīng)頭解決跨域

@RequestMapping(value = "/user-1")
public User getUser_1(HttpServletResponse response ) {

    // 允許所有,不安全
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Max-Age", "10");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
    response.setHeader("Access-Control-Allow-Credentials", "true");

    
    return new User(1L, "Booker", "admin", "sdfsdkjf93hu8dvn");
}

5、使用自定義filter實(shí)現(xiàn)跨域

public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new MyCorsFilter());
        bean.addUrlPatterns("/*");
        return bean;
    }
}

總結(jié)

到此這篇關(guān)于SpringBoot項(xiàng)目中如何解決跨域問(wèn)題的最新方案?的文章就介紹到這了,更多相關(guān)SpringBoot解決跨域問(wèn)題內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論