天天看點

後端方法解決前後端分離開發跨域問題

使用前端方法解決跨域問題,詳見我的第一篇部落格;這裡不再贅述。

Access to XMLHttpRequest at 'http://localhost:9090/user/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我們這裡直接寫了個配置檔案CorsConfig.java解決跨域問題(可複制粘貼直接拿去用):

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 CorsConfig {

    // 目前跨域請求最大有效時長。這裡預設1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 設定通路源位址
        corsConfiguration.addAllowedHeader("*"); // 2 設定通路源請求頭
        corsConfiguration.addAllowedMethod("*"); // 3 設定通路源請求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 對接口配置跨域設定
        return new CorsFilter(source);
    }
}
      

這樣可以很好的解決前後端分離開發中的跨域問題。