java解決跨域問題


項目場景:

練習黑馬樂優商城項目遇到跨域問題,總結跨域

問題描述:

瀏覽器控制台出現"No 'Access-Control-Allow-Origin"

在這里插入圖片描述

什么是跨域

在這里插入圖片描述

為什么會有跨域問題

在這里插入圖片描述

解決跨域問題的方案

Jsonp

在這里插入圖片描述

Nginx反向代理

在這里插入圖片描述

CORS

在這里插入圖片描述

CORS解決跨域

什么是CORS

在這里插入圖片描述

CORS原理

瀏覽器會將ajax請求分為兩類,其處理方案略有差異:簡單請求、特殊請求

簡單請求

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

特殊請求

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

有沒有CORS區別

在這里插入圖片描述

SpringMVC實現CORS

在這里插入圖片描述
在這里插入圖片描述

package com.leyou.gateway.config;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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;

import java.util.Arrays;

/**
 * @Date: Created in 9:40 2021/2/8
 */
@Configuration
@EnableAutoConfiguration
public class CORSFilter {
    /**
     * 注冊過濾器bean,設置跨域規則
     */
    @Bean
    public CorsFilter corsFilter() {
        //配置CORS相關規則
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允許哪些域名可以跨域訪問
        corsConfiguration.setAllowedOrigins(Arrays.asList("http://manage.leyou.com","http://localhost:9001"));
        //允許哪些提交方式可以訪問
        corsConfiguration.setAllowedMethods(Arrays.asList("GET","PUT","DELETE","POST","OPTIONS"));
        //允許哪些請求頭可以訪問
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        //是否允許操作cookie
        corsConfiguration.setAllowCredentials(true);
        //設置預檢請求有效期
        corsConfiguration.setMaxAge(1800L);
        //配置攔截請求路徑
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        CorsFilter corsFilter = new CorsFilter(source);
        return corsFilter;
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM