什么是跨域?
跨域资源共享(CORS) 是一种机制,它使用额外的 HTTP 头来告诉浏览器 让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源。当一个资源从与该资源本身所在的服务器不同的域、协议或端口请求一个资源时,资源会发起一个跨域 HTTP 请求。
比如:http://cyun.top
http://cyun.top/home 不跨域
http://cyun.top:8080 跨域 端口不同
https://cyun.top 跨域 协议不同
http://admin.cyun.top 跨域 域名不同
常见跨域解决几种方式
1、使用@CrossOrigin
a.方法上加
@CrossOrigin(origins = "*")
@PostMapping("/login")
public String login(@RequestBody User user){
return "";
}
b.类上加(origin="*" 代表所有域名都可访问 maxAge表示Cookie的有效期 单位为秒)
@CrossOrigin(origins = "*",maxAge = 1800)
public class UserController {
}
2、使用WebMvcConfigurer 配置
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);
}
}
3、使用CorsFilter
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 {
@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);
}
}
4、网关配置(springcloud)
spring:
application:
name: gateway-service
profiles:
active: default
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*" #跨域处理运行所有跨域
allowedMethods: #支持方法
-GET
-POST
-PUT
-DELETE
allowedHeaders: "*"
allowCredentials: true