Java解決跨域問題

Blue啊發表於2024-04-04
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.CorsRegistry;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  

@Configuration  
public class CorsConfig {  

    @Bean  
    public WebMvcConfigurer corsConfigurer() {  
        return new WebMvcConfigurer() {  
            @Override  
            public void addCorsMappings(CorsRegistry registry) {  
                registry.addMapping("/**")  
                        .allowedOrigins("http://127.0.0.1:5173") // 允許訪問的源  
                        .allowedMethods("GET", "POST", "PUT", "DELETE") // 允許的HTTP方法  
                        .allowedHeaders("*") // 允許的請求頭  
                        .allowCredentials(true); // 是否傳送cookie  
            }  
        };  
    }  
}

相關文章