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

相关推荐
fire-flyer几秒前
设计模式之观察者模式
java·开发语言
倚栏听风雨7 分钟前
git "base点"详解,顺便解释merge和rebase区别
后端
掘金一周29 分钟前
重新思考 weapp-tailwindcss 的未来 | 掘金一周 11.13
前端·人工智能·后端
⑩-31 分钟前
苍穹外卖Day(1)
java·数据库·spring boot·spring·java-ee·mybatis
程序员buddha39 分钟前
C语言操作符详解
java·c语言·算法
小生凡一42 分钟前
图解|Go语言实现 Agent|LLM+MCP+RAG
开发语言·后端·golang
l0sgAi1 小时前
SpringAI 整合MCP实现联网搜索 (基于tavily)
java·后端
朝新_1 小时前
【统一功能处理】从入门到源码:拦截器学习指南(含适配器模式深度解读)
数据库·后端·mybatis·适配器模式·javaee
q***7481 小时前
私有化部署DeepSeek并SpringBoot集成使用(附UI界面使用教程-支持语音、图片)
spring boot·后端·ui