关于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项目常见的跨域解决方式。
文中如果错误或不当之处,欢迎指正~~