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

API处理请求30秒后触发CORS错误,求助排查(附配置)

跨域问题排查与解决(请求超时30秒触发CORS错误)

问题背景

已配置Nginx反向代理CORS规则、FastAPI的CORSMiddleware允许所有源,但当API处理请求超过30秒时,浏览器触发CORS错误。使用Cloudflare代理api.company.com的DNS记录,请求路由到本地8000端口的FastAPI服务。

组件配置信息

1. API的Nginx代理配置

server {
    listen 80;
    server_name api.company.com;

    location / {
        # Handle preflight requests
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization' always;
            add_header 'Access-Control-Max-Age' 1728000;  # Cache preflight response for 20 days
            add_header 'Content-Length' 0 always;
            return 204;  # No content
        }

        # Proxy settings for other methods
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Timeout settings
        proxy_connect_timeout 90s;
        proxy_send_timeout 90s;
        proxy_read_timeout 90s;
        send_timeout 90s;
    }
}

2. UI端代码与Nginx配置

React Query代码

export const quality_control = (body) =>
    qc_api.post("/quality_control", body).then((e) => {
        return e.data;
    });
const useQualityCheck = () => {
 
    return useMutation({
        mutationFn: quality_control,
        onSuccess: (data) => {
            if (data.success === true) {
                console.log("success response", data.message);
            } else {
                console.log("error response", data.message);
            }
        },
        onError: (error) => {
            if (error.response) {
                console.log("error response", error);
            }
        },
 
    });
};

UI的Nginx配置

server {
    listen 80;
    server_name ui.company.com;

    # Forward requests to the React app running on port 8080
    location / {
        proxy_pass http://localhost:8080;  # React app running on port 8080
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

3. FastAPI后端配置与API函数

后端配置

app = FastAPI(
    **fastapi_kwargs,
    swagger_ui_parameters={"defaultModelsExpandDepth": -1},
    middleware=[
        Middleware(
                CORSMiddleware,                                                        allow_headers=["*"],
            allow_credentials=True,
            allow_origins=["*"],
            allow_methods=["*"],
        ),
    ],
)

API处理函数

def check_quality_control(
    request: Request,
    payload: CheckQualityControlRequestModel = Depends(
        CheckQualityControlRequestModel.as_multipart_form
    ),
) -> CheckQualityControlResponseModel:
    result = llava_next.evaluate_image(
        car_image=payload.image,
        model=request.app.state.model,
        processor=request.app.state.processor,
    )

    # Remove unwanted data
    data_to_remove = ["image", "prompt", "output"]
    result = {key: value for key, value in result.items() if key not in data_to_remove}

    formatted_feedback = {}
    for key, value in result.items():
        for _, text in value.items():
            # Extract the score from the text
            score_index = text.rfind("Score:")
            score = text[score_index + len("Score:") :].strip()
            feedback_text = text[:score_index].strip()

            # Format the result
            formatted_feedback[key] = {
                "Feedback": feedback_text,
                "Score": score,
            }
    return CheckQualityControlResponseModel(**formatted_feedback)

浏览器报错信息

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.company.comi/quality_control. (Reason: CORS request did not succeed). Status code: (null)

排查与解决步骤

  • 修正请求地址拼写错误:报错中的地址为https://api.company.comi/quality_control,多了一个i,需确认UI端请求的URL是否正确,这是可能直接导致请求失败的原因。
  • 调整Cloudflare超时设置:Cloudflare默认HTTP请求超时为30秒,API处理超时时会被提前中断,浏览器收到不完整响应后误报CORS错误。需在Cloudflare控制台:
    1. 进入对应域名的规则 -> 页面规则
    2. 创建匹配api.company.com/*的规则
    3. 将HTTP请求超时调整为90秒(与Nginx超时设置一致)
  • 统一CORS配置避免冲突:Nginx和FastAPI同时配置CORS可能导致响应头冲突,建议保留FastAPI的CORSMiddleware,修改Nginx配置移除OPTIONS请求处理块:
    server {
        listen 80;
        server_name api.company.com;
    
        location / {
            proxy_pass http://localhost:8000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
    
            # Timeout settings
            proxy_connect_timeout 90s;
            proxy_send_timeout 90s;
            proxy_read_timeout 90s;
            send_timeout 90s;
        }
    }
    
  • 调整FastAPI服务器超时:Uvicorn默认超时可能低于90秒,启动时需添加参数:
    uvicorn main:app --host 0.0.0.0 --port 8000 --timeout-keep-alive 90 --timeout-graceful-shutdown 120
    
  • 修改UI端请求超时:React Query依赖的请求实例(如Axios)默认超时可能为30秒,需调整:
    // 假设qc_api是Axios实例,设置90秒超时
    const qc_api = axios.create({
      baseURL: 'https://api.company.com',
      timeout: 90000,
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:40:24