跨域的概念
参考文章:https://www.cnblogs.com/zyndev/p/13697313.html
端口,协议,域名(IP)有一个不同就会产生跨域问题
- 域名不同:
-
- 例如,当前页面的域名为 www.example.com,而请求的资源的域名为 api.example.com。
- 协议不同:
-
- 例如,当前页面的协议为 https,而请求的资源的协议为 http。
- 端口号不同:
-
- 例如,当前页面的端口号为 8080,而请求的资源的端口号为 9090。
跨域问题指的是在 Web 应用程序中,由于同源策略的限制,导致浏览器无法发送跨域请求,也无法获取跨域响应的问题。同源策略是浏览器的一种安全策略,它要求 Web 应用程序只能访问与当前页面具有相同协议、主机名和端口号的资源。
CORS 实现跨域资源共享(解决跨域)
跨域(CORS)是指不同域名之间相互访问。CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
SpringBoot 解决跨域
方式一:使用@CrossOrigin注解
@CrossOrigin注解中的origins属性表示允许跨域请求的源地址,多个地址可以用逗号分隔。如果不指定该属性,则表示允许所有来源的请求
加在控制类
@CrossOrigin
@RestController
public class UserController {
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
}
}
加在方法上
@RestController
public class UserController {
@CrossOriginn(origins ="http://localhost:8080")
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
}
}
方式二:使用WebMvcConfigurer
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 拦截所有的请求
.allowedOrigins("http://www.abc.com") // 可跨域的域名,可以为 *
.allowCredentials(true)
.allowedMethods("*") // 允许跨域的方法,可以单独配置
.allowedHeaders("*"); // 允许跨域的请求头,可以单独配置
}
}
方式三:使用 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 configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",configuration);
return new CorsFilter(source);
}
}
SpringCloud 解决跨域
Gateway 跨域配置
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
# 允许跨域的源(网站域名/ip),设置*为全部
# 允许跨域请求里的head字段,设置*为全部
# 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
allow-credentials: true
allowed-origins:
- "http://xb.abc.com"
- "http://sf.xx.com"
allowed-headers: "*"
allowed-methods:
- OPTIONS
- GET
- POST
- DELETE
- PUT
- PATCH
max-age: 3600