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

Postman可接收FastAPI响应,React却无法接收的解决方法

React fetch无法接收FastAPI异常处理器返回的响应(Postman正常)

问题背景

FastAPI服务运行在localhost:8000,React开发服务在localhost:3000。创建用户的POST端点会检查邮箱是否存在:存在则触发自定义异常,由异常处理器返回JSON响应;不存在则创建用户并返回认证信息。

终端日志显示请求已到达端点且触发了异常处理器,但React的fetch无法接收响应,Postman却能正常接收。已配置CORS中间件允许所有来源,排除跨域问题。

核心原因

你的React fetch代码存在两个关键问题:

  1. 未正确处理HTTP错误状态码:fetch API仅在网络故障时抛出异常,HTTP错误状态码(如409冲突)不会自动触发Promise拒绝,需要手动检查响应状态。
  2. 未解析响应体:直接打印response.body得到的是ReadableStream对象,无法读取实际的JSON响应内容。

解决方案

1. 修复React fetch的响应处理逻辑

修改createUserSignUpSubmit函数,添加状态检查和响应体解析:

const createUserSignUpSubmit = async () => {
    try {
        const response = await fetch('http://localhost:8000/authentication/create_user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "user": {
                    "email": "user@example.com",
                    "password": "string",
                    "first_name": "string",
                    "last_name": "string",
                    "dob": "2019-08-24"
                }
            })
        });

        // 检查响应是否成功
        if (!response.ok) {
            const errorData = await response.json();
            console.error('注册失败:', errorData);
            alert(errorData.detail || '邮箱已存在');
            return;
        }

        // 解析成功响应
        const successData = await response.json();
        console.log('注册成功:', successData);
        
        // 清空表单
        setFirstName('');
        setLastName('');
        setEmail('');
        setPassword('');
        setDate(new Date());
    } catch (error) {
        console.error('网络错误:', error);
        alert('网络连接失败,请稍后重试');
    }
};

2. 确认异常处理器的状态码与CORS配置

  • 确保EmailAlreadyExistsException的status_code使用标准HTTP错误码(比如409代表资源冲突),避免使用2xx系列状态码(会被fetch判定为成功响应)。
  • 若CORS自动处理失效,可手动为异常响应添加CORS头:
@app.exception_handler(EmailAlreadyExistsException)
def email_exists_exception_handler(request: Request, exc: EmailAlreadyExistsException):
    print('here')
    response = JSONResponse(
        status_code=exc.status_code,
        content=jsonable_encoder({'detail': exc.description})
    )
    # 手动添加CORS头(仅在自动配置失效时使用)
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response

验证步骤

  1. 修改代码后,测试注册已存在的邮箱,查看浏览器控制台是否打印出错误响应的detail内容。
  2. 打开浏览器Network面板,查看该POST请求的Response标签,确认是否返回了正确的JSON内容和状态码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:10:24