springboot如何配置允許跨域訪問
更新時間:2024年08月09日 09:52:05 作者:L若兒
這篇文章主要介紹了springboot如何配置允許跨域訪問,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
springboot配置允許跨域訪問
因springboot框架通常用于前后端分離項目,因此需配置后臺允許跨域訪問(具體看注釋),
配置類如下,將該類加入工程中即可。
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;
/**
* @author suntongxin
* Create on 2017年7月6日下午8:05:19
* All right reserved
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允許任何域名
corsConfiguration.addAllowedHeader("*"); //允許任何頭
corsConfiguration.addAllowedMethod("*"); //允許任何方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注冊
return new CorsFilter(source);
}
}前后端分離跨域問題的解決
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 {
// 當(dāng)前跨域請求最大有效時長。我設(shè)置的是一天的時間
private static final long MAX_AGE = 24 * 60 * 60;
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 設(shè)置訪問源地址
corsConfiguration.addAllowedHeader("*"); // 設(shè)置訪問源請求頭
corsConfiguration.addAllowedMethod("*"); // 設(shè)置訪問源請求方法
corsConfiguration.setMaxAge(MAX_AGE);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 對接口配置跨域設(shè)置
return new CorsFilter(source);
}
}
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis-Plus自動填充更新操作相關(guān)字段的實現(xiàn)
這篇文章主要介紹了Mybatis-Plus自動填充更新操作相關(guān)字段的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
spring cloud gateway 如何修改請求路徑Path
這篇文章主要介紹了spring cloud gateway 修改請求路徑Path的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
JAVA?兩個類同時實現(xiàn)同一個接口的方法(三種方法)
在Java中,兩個類同時實現(xiàn)同一個接口是非常常見的,接口定義了一組方法,實現(xiàn)接口的類必須提供這些方法的具體實現(xiàn),以下將展示如何實現(xiàn)這一要求,并提供具體的代碼示例,需要的朋友可以參考下2024-08-08
volatile與happens-before的關(guān)系與內(nèi)存一致性錯誤
本文講了Java并發(fā)編程中volatile變量、happens-before與內(nèi)存一致性錯誤,下面來和小編一起學(xué)習(xí)下如何解決2019-05-05

