SpringBoot 解决跨域问题

在Spring Boot中,解决跨域问题可以通过配置CORS(Cross-Origin Resource Sharing)来实现。以下是一些解决跨域问题的步骤:

1.添加依赖

在pom.xml文件中添加以下依赖:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.配置CORS

在Spring Boot中,可以通过在application.properties或application.yml文件中配置CORS来解决跨域问题。以下是一些示例配置:

在application.properties中配置:

spring.web.cors.allowed-origins=http://example.com,http://localhost:3000
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
spring.web.cors.max-age=3600

在application.yml中配置:

spring:

web:

cors:

allowed-origins:

allowed-methods:

  • GET

  • POST

  • PUT

  • DELETE

allowed-headers:

  • Content-Type

  • X-Requested-With

  • accept

  • Origin

  • Access-Control-Request-Method

  • Access-Control-Request-Headers

max-age: 3600

上述配置中,allowed-origins指定了允许跨域访问的来源,可以是一个域名或一个IP地址。allowed-methods指定了允许的HTTP方法,如GET、POST等。allowed-headers指定了允许的请求头,可以根据需要进行添加。max-age指定了预览时间,单位为秒。

3.启用CORS

在SpringBoot中,CORS默认是关闭的。需要在控制器类上添加@CrossOrigin注解来启用CORS。例如:

@RestController
@CrossOrigin(origins = "http://example.com", methods = "*", allowedHeaders = "*")
public class MyController {

// ...
}

在上述示例中,@CrossOrigin注解指定了允许跨域访问的来源、HTTP方法和请求头。可以根据需要进行修改。

通过以上步骤,可以解决Spring Boot中的跨域问题。

相关推荐
牧羊人_myr2 分钟前
Maven核心功能与项目构建详解
java·maven
华仔啊14 分钟前
千万级大表如何新增字段?别再直接 ALTER 了
后端·mysql
IT_陈寒18 分钟前
Python开发者必看!10个高效数据处理技巧让你的Pandas代码提速300%
前端·人工智能·后端
量子物理学21 分钟前
Eclipse Mosquitto 在小内存下怎么修改配置文件
java·服务器·eclipse
程序员鱼皮33 分钟前
让老弟做个数据同步,结果踩了 7 个大坑!
java·后端·计算机·程序员·编程·职场
麦兜*41 分钟前
Redis 7.2 新特性实战:Client-Side Caching(客户端缓存)如何大幅降低延迟?
数据库·spring boot·redis·spring·spring cloud·缓存·tomcat
Iris76142 分钟前
MyBatis一对多关系映射方式
java
程序员清风42 分钟前
滴滴二面:MySQL执行计划中,Key有值,还是很慢怎么办?
java·后端·面试
白鲸开源42 分钟前
3.1.8<3.2.0<3.3.1,Apache DolphinScheduler集群升级避坑指南
java·开源·github
huohaiyu1 小时前
synchronized (Java)
java·开发语言·安全·synchronized