You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端对接Java Spring Boot API遇CORS拦截及全栈部署AWS问题咨询

解决方案:前端+Spring Boot(JPA)对接及AWS部署

一、先解决CORS跨域问题

1. 全局CORS配置(推荐,全接口生效)

创建配置类,统一允许指定来源的跨域请求:

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.addAllowedOrigin("http://127.0.0.1:5500");
        // 允许所有请求方法(GET/POST/PUT等)
        config.addAllowedMethod("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许携带Cookie(按需开启)
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有接口生效
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

2. 局部接口配置(单接口/Controller生效)

在目标Controller或接口方法上添加@CrossOrigin注解:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 允许本地前端跨域
@CrossOrigin(origins = "http://127.0.0.1:5500")
public class DemoController {
    @GetMapping("/api/test")
    public String test() {
        return "Hello from Spring Boot!";
    }
}

二、前端→API→Spring Boot→PostgreSQL链路实现

1. 后端Spring Boot(JPA)配置

(1)依赖配置(pom.xml)

确保添加核心依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

(2)数据库配置(application.properties)

spring.datasource.url=jdbc:postgresql://localhost:5432/你的数据库名
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

(3)核心代码示例

// 实体类
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // 省略getter、setter、构造方法
}

// Repository接口(自动实现CRUD)
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

// Controller(对外提供API)
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://127.0.0.1:5500")
public class UserController {
    private final UserRepository userRepository;

    // 构造方法注入依赖
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 获取所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 创建新用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
}

2. 前端fetch请求示例

// 获取用户列表
fetch('http://localhost:8080/api/users')
    .then(response => response.json())
    .then(data => console.log('用户列表:', data))
    .catch(error => console.error('请求失败:', error));

// 创建新用户
const newUser = { name: '张三', email: 'zhangsan@example.com' };
fetch('http://localhost:8080/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log('创建成功:', data))
.catch(error => console.error('创建失败:', error));

三、全栈应用部署至AWS

1. 数据库部署:AWS RDS PostgreSQL

  • 登录AWS控制台进入RDS服务,创建PostgreSQL实例:
    • 选择"免费套餐"(测试用),设置实例名、用户名、密码
    • 配置安全组,允许后端服务的IP访问5432端口
    • 实例创建完成后,记录端点地址、端口、账号信息
  • 修改Spring Boot的application.properties,替换为RDS配置:
spring.datasource.url=jdbc:postgresql://你的RDS端点:5432/数据库名
spring.datasource.username=RDS用户名
spring.datasource.password=RDS密码

2. 后端部署:AWS Elastic Beanstalk

  • 打包Spring Boot应用:在项目根目录执行mvn clean package,得到target/项目名.jar
  • 登录AWS控制台进入Elastic Beanstalk服务,创建应用:
    • 选择"Web服务器环境",平台选"Java",上传打包好的jar包
    • 部署完成后,记录BeanStalk的域名(如xxx.elasticbeanstalk.com)
  • 修改前端fetch的请求地址为该域名,比如https://xxx.elasticbeanstalk.com/api/users

3. 前端部署:AWS S3 + CloudFront

  • 登录AWS控制台进入S3服务,创建存储桶:
    • 存储桶名需唯一,取消"阻止所有公共访问",添加桶策略允许公共读取:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::你的存储桶名/*"
        }
    ]
}
  • 开启静态网站托管,设置索引文档为index.html
  • 上传前端的HTML/CSS/JS文件到存储桶
  • (可选)配置CloudFront分发,绑定自定义域名并开启HTTPS,提升访问安全性和速度

4. 跨域配置调整

部署后,修改Spring Boot的CORS配置,将允许的来源替换为前端的S3/CloudFront域名:

config.addAllowedOrigin("https://你的前端域名");

内容的提问来源于stack exchange,提问作者wbh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:55:36