關於SpringBoot/Cloud項目的跨域的幾種解決方案
跨域資源共享(CORS) 是一種機制,它使用額外的 HTTP 頭來告訴瀏覽器 讓運行在一個 origin (domain) 上的Web應用被准許訪問來自不同源服務器上的指定的資源。當一個資源從與該資源本身所在的服務器不同的域、協議或端口請求一個資源時,資源會發起一個跨域 HTTP 請求。
比如,站點http://domain-a.com
的某 HTML 頁面通過<img>
的 src 請求http://domain-b.com/image.jpg
。網絡上的許多頁面都會加載來自不同域的CSS樣式表,圖像和腳本等資源。
出於安全原因,瀏覽器限制從腳本內發起的跨源HTTP請求。 例如,XMLHttpRequest和Fetch API遵循同源策略。 這意味着使用這些API的Web應用程序只能從加載應用程序的同一個域請求HTTP資源,除非響應報文包含了正確CORS響應頭。
本文介紹一下Spring Boot / Spring Cloud項目常見的幾種跨域解決方案。
1. 使用@CrossOrigin
註解
@CrossOrigin(origins = "*")
@PostMapping("/login")
public R login(@RequestBody LoginForm form){
// do login
return R.ok();
}
也可以標註在類上,表示類的所有方法允許跨域,註解源碼如下:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
//...
}
2. 使用CorsFilter
配置全局跨域
package org.xudc.mall.gateway.config;
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 xudc
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration config = new CorsConfiguration();
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
3. 實現WebMvcConfigurer
配置全局跨域
package org.xudc.manager.config;
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 implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(1800);
}
}
4. 配置文件實現全局跨域
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': # 表示攔截 /**所有請求
allowedOrigins: "*"
allowedMethods: "*"
# - GET
allowedHeaders: "*"
allowCredentials: true
以上就是Spring Boot / Spring Cloud項目常見的跨域解決方式。
文中如果錯誤或不當之處,歡迎指正~~