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

React向FastAPI发请求遭CORS跨域拦截,已配置中间件仍求助

React前端调用FastAPI后端POST接口的CORS问题解决

我正尝试从运行于http://localhost:5173的React前端,向运行于http://localhost:8000的FastAPI后端发送POST请求,上传图片文件调用结核病预测接口。尽管已在后端配置了CORSMiddleware,但调用callPrediction函数时仍弹出“origin http://localhost:5173 has been blocked by CORS policy”错误。

后端FastAPI代码

from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import numpy as np
import tensorflow as tf
from io import BytesIO
from PIL import Image

app = FastAPI()

origins = ["http://localhost:5173/"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

model = tf.keras.models.load_model("../models/1")
class_names = ["Normal", "Tuberculosis"]

def convert_image_to_np_array(bytes):
    # Read bytes as PIL image and convert it to np array
    np_array = np.array(Image.open(BytesIO(bytes)))
    return np_array

@app.post("/predict")
async def predict_tuberculosis(file: UploadFile):
    bytes = await file.read()
    np_array = convert_image_to_np_array(bytes)
    batch_image = np.expand_dims(np_array, axis=0)
    resized_batch_image = np.resize(batch_image, (1,256,256,3))
    prediction = model.predict(resized_batch_image)
    label = class_names[np.argmax(prediction)]
    accuracy = np.max(prediction)
    print(accuracy)
    return label

前端React代码

import React from "react"
import { useState } from "react"
import axios from "axios"
import "./App.css"

function App() {
  function callPrediction(file) {
    const formData = new FormData()
    formData.append("file", file)
    axios.post("http://localhost:8000/predict", formData)
    .then(res => setResult(res.data))
    .catch(err => console.log(err))
  }

  // 其余代码省略
}

相关信息

  • 文件输入格式:为标准File对象,包含name、lastModified、size等属性
  • 触发的错误信息:origin http://localhost:5173 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

问题排查与解决方法

1. 修正Origin地址的斜杠问题

后端配置的origins = ["http://localhost:5173/"]末尾带有斜杠,但浏览器发送的Origin请求头是http://localhost:5173(不带斜杠),FastAPI的CORSMiddleware对Origin的匹配是严格精确匹配,这会导致CORS校验失败。

解决:将origins改为不带斜杠的地址:

origins = ["http://localhost:5173"]

如果需要兼容带斜杠的情况,也可以使用通配符(仅建议开发环境使用,生产环境需明确指定Origin):

origins = ["http://localhost:5173*"]

2. 验证CORS配置是否生效

可以通过curl命令发送OPTIONS预检请求,检查响应头是否包含正确的CORS信息:

curl -X OPTIONS http://localhost:8000/predict -H "Origin: http://localhost:5173" -v

正常情况下,响应头应包含Access-Control-Allow-Origin: http://localhost:5173。

3. 前端请求补充配置

由于后端设置了allow_credentials=True,前端axios请求需要添加withCredentials: true参数,确保跨域请求携带凭证:

axios.post("http://localhost:8000/predict", formData, { withCredentials: true })
.then(res => setResult(res.data))
.catch(err => console.log(err))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:12:48