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

Postman可创建账号,React端注册请求报POST 415错误求助

排查React + Spring Boot POST请求415及JSON解析错误的方案

哈,这个问题我之前也踩过坑!核心问题大概率出在你设置的mode: 'no-cors'上,咱们一步步拆解:

1. 罪魁祸首:mode: 'no-cors'

当你开启no-cors模式时,浏览器会把请求变成不透明请求(opaque request),带来两个致命问题:

  • 浏览器会强制忽略你自定义的Content-Type: application/json请求头,自动降级为text/plain,这直接导致Spring Boot后端收到的不是预期的JSON格式,返回415 Unsupported Media Type错误。
  • 你完全无法读取响应内容,调用res.json()时自然会抛出Unexpected end of input——因为响应体根本无法被访问和解析。

Postman能正常请求,正是因为它不受浏览器的跨域限制,能正确发送Content-Type头并读取响应。

2. 修复步骤

第一步:移除mode: 'no-cors'

修改你的fetch代码,删掉这个配置项,同时增加响应状态检查避免无效解析:

handleRegisterSubmit(e, data) {
    console.log('submitting')
    let stringer = JSON.stringify(data)
    console.log(stringer)
    e.preventDefault()
    fetch('/api/register', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        credentials: 'include',
        // 删掉这一行:mode: 'no-cors',
        body: JSON.stringify(data)
    }).then(res => {
        // 先检查响应状态,避免非2xx状态码直接解析JSON
        if (!res.ok) {
            throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json()
    }).then(res => {
        console.log(res)
        this.setState({ auth: res.auth, user: res.data.user })
    }).catch(err => console.log(err))
}

第二步:配置Spring Boot的CORS支持

移除no-cors后,浏览器会发送OPTIONS预检请求,你需要在后端配置跨域:

  • 局部配置:在你的注册接口控制器上添加@CrossOrigin注解:
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:3000", credentials = true) // 替换成你的React前端地址
public class AuthController {
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserRegistrationDto dto) {
        // 你的注册逻辑
    }
}
  • 全局配置(推荐,适合多个接口):
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

3. 额外排查点

  • 检查浏览器Network面板:去掉no-cors后,你可以看到实际发送的请求头(确认Content-Type是否为application/json)、请求体是否正确,以及后端的响应详情。
  • 确认Spring Boot接口的@RequestBody注解:确保你用了@RequestBody来接收JSON格式的请求体,并且DTO类的字段和前端发送的JSON结构完全匹配。
  • 验证请求体:虽然你已经打印了stringer,但可以在Network面板里查看Request Payload,确认和Postman发送的完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:06:00