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中的跨域问题。

相关推荐
Java致死18 分钟前
单例设计模式
java·单例模式·设计模式
胡子发芽22 分钟前
请详细解释Java中的线程池(ThreadPoolExecutor)的工作原理,并说明如何自定义线程池的拒绝策略
java
沫夕残雪27 分钟前
Tomcat的安装与配置
java·tomcat
Rabbb35 分钟前
C# JSON属性排序、比较 Newtonsoft.Json
后端
蓝易云36 分钟前
在Linux、CentOS7中设置shell脚本开机自启动服务
前端·后端·centos
胡子发芽39 分钟前
请解释Java中的NIO(New I/O)与传统I/O的区别,并说明NIO中的关键组件及其作用
java
一千柯橘43 分钟前
Nestjs 解决 request entity too large
javascript·后端
柚个朵朵1 小时前
IDEA中使用Git
java·git·spring
userkang1 小时前
消失的前后端,崛起的智能体
前端·人工智能·后端·ai·硬件工程
jerry6091 小时前
优先队列、堆笔记(算法第四版)
java·笔记·算法