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

Spring Boot服务无法接收FetchAPI请求,报403错误求助

问题:表单提交至Spring Boot服务时出现403错误

我编写了以下JavaScript函数用于获取表单数据并发送到Spring Boot服务:

function saveDataToStorage(event){
            event.preventDefault();
            let name = document.getElementById('imie').value;
            let email = document.getElementById('email').value;
            let phone = document.getElementById('telefon').value;
            let topic = document.getElementById('temat').value;
            let message = document.getElementById('wiadomosc').value;
            let data = {
                name: name,
                email: email,
                phoneNumber: phone,
                topic: topic,
                text: message
            }

            fetch('http://localhost:8080/api/endpoint',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
                .then(response => response.json())
                .then(data => {console.log('Success:',data);})
                .then(error => {console.log('Error:',error);});

            document.getElementById('imie').value = '';
            document.getElementById('email').value = '';
            document.getElementById('telefon').value = '';
            document.getElementById('temat').value = '';
            document.getElementById('wiadomosc').value = '';
        }

后端定义了FormData实体类:

@Data
@AllArgsConstructor
public class FormData {
    String name;
    String email;
    String phoneNumber;
    String topic;
    String message;
}

以及POST接口:

@PostMapping("/api/endpoint")
    public ResponseEntity<String> receiveData(@RequestBody FormData data){
        log.info(data.getName()+" "+data.getEmail()+" "+data.getPhoneNumber()+" "+data.getTopic()+" "+data.getMessage());
        return ResponseEntity.ok("data recieved");
    }

提交表单时出现错误:

Failed to load resource: the server responded with a status of 403 ()

Spring应用控制台无任何报错信息。我已尝试在安全配置中对该接口放行:

http.authorizeHttpRequests(authz->authz
.requestMatchers("/api/endpoint").permitAll()

但问题仍未解决。


解决方案

1. 配置跨域(CORS)

前端与后端端口/域名不一致时会触发跨域限制,Spring Security默认拦截跨域请求。可通过两种方式配置:

  • 全局CORS配置:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:你的前端端口") // 替换为实际前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}
  • 接口级注解:
@PostMapping("/api/endpoint")
@CrossOrigin(origins = "http://localhost:你的前端端口")
public ResponseEntity<String> receiveData(@RequestBody FormData data){
    // 原有代码逻辑
}

2. 补全Spring Security配置

你的安全配置代码不完整,需确保配置逻辑闭合,同时检查CSRF设置:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable()) // 开发环境可临时关闭,生产环境需配置CSRF令牌
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/api/endpoint").permitAll()
                        .anyRequest().authenticated()
                );
        return http.build();
    }
}

说明:POST请求默认受CSRF保护,前端未携带令牌会触发403,开发阶段可临时关闭CSRF调试,生产环境需在前端添加获取并携带CSRF令牌的逻辑。

3. 修正字段映射错误

前端请求体中字段为text,但后端FormData类对应字段是message,会导致JSON反序列化失败,需修改前端数据结构:

let data = {
    name: name,
    email: email,
    phoneNumber: phone,
    topic: topic,
    message: message // 替换原有的text字段
}

4. 确认请求路径匹配

若Spring Boot配置了server.servlet.context-path,前端请求URL需加上对应前缀,比如上下文路径为/app,则请求地址应为http://localhost:8080/app/api/endpoint。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:30:55