java B2B2C 源碼 多級分銷Springboot多租戶電子商城系統-前端跨域問題的解決方案

當我們需要將spring boot以restful接口的方式對外提供服務的時候,如果此時架構是前後端分離的,那麼就會涉及到跨域的問題,那怎麼來解決跨域的問題了,下面就來探討下這個問題。

解決方案一:在Controller上添加@CrossOrigin註解

使用方式如下:


@CrossOrigin // 註解方式
@RestController
public class HandlerScanController {
    
    
    @CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,
            RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS,
            RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins="*")
    @PostMapping("/confirm")
    public Response handler(@RequestBody Request json){
        
        return null;
    }
}

解決方案二:全局配置
代碼如下:


@Configuration
    public class MyConfiguration {
 
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                    .allowCredentials(true)
                    .allowedMethods("GET");
                }
            };
        }
    }

解決方案三:結合Filter使用
在spring boot的主類中,增加一個CorsFilter



/**
     * 
     * attention:簡單跨域就是GET,HEAD和POST請求,但是POST請求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
     * 反之,就是非簡單跨域,此跨域有一個預檢機制,說直白點,就是會發兩次請求,一次OPTIONS請求,一次真正的請求
     */
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // 允許cookies跨域
        config.addAllowedOrigin("*");// #允許向該服務器提交請求的URI,*表示全部允許,在SpringMVC中,如果設成*,會自動轉成當前請求頭中的Origin
        config.addAllowedHeader("*");// #允許訪問的頭信息,*表示全部
        config.setMaxAge(18000L);// 預檢請求的緩存時間(秒),即在這個時間段裏,對於相同的跨域請求不會再預檢了
        config.addAllowedMethod("OPTIONS");// 允許提交請求的方法,*表示全部允許
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");// 允許Get的請求方法
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

java B2B2C 源碼 多級分銷Springcloud多租戶電子商城系統來源

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章