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

React与Flask(Python)图片上传整合时的CORS预检请求失败问题

Fixing CORS Issue in React-Flask Image Upload

Hey there, let’s work through this CORS problem you’re facing—this is super common when connecting a frontend (React) to a backend (Flask), so we’ll get it sorted quickly!

First, Let’s Understand the Error

The error says your preflight (OPTIONS) request didn’t return a successful HTTP status. Here’s the key mistake: you’re adding the Access-Control-Allow-Origin header to your React fetch request. This header belongs on the server’s response, not the client’s request. The browser checks for this header from the Flask backend to allow cross-origin requests—sending it from React does nothing to fix the issue.


Step 1: Fix the React Fetch Code

First, clean up your fetch call by removing the incorrect header, and fix the undefined str1 variable (which would break your request URL anyway):

_results(){
  // First, define str1 with your actual Flask endpoint path (replace with your value!)
  const str1 = "abc"; // Based on your error message's /abc/qwerty.jpg path
  const requestUrl = `http://0.0.0.0:4000/${str1}/${this.state.path}`;

  fetch(requestUrl, {
    method: "POST",
    // Remove the Access-Control-Allow-Origin header from the request
    headers: {
      "Content-Type": "application/json", // Adjust based on your Flask API's expected content type
    },
  })
  .then(res => {
    // Add error handling for non-success status codes
    if (!res.ok) {
      throw new Error(`Request failed with status: ${res.status}`);
    }
    return res.json();
  })
  .then(res => {
    const pathSegment = window.location.pathname.split("/")[4];
    if(pathSegment === "gender"){
      this.setState({ res: res.Gender });
    } else if(pathSegment === "emotion"){
      this.setState({ res: res.Emotion });
    }
  })
  .catch(err => console.error("Fetch error:", err));
}

Also, note: Your current code only sends the filename to Flask, not the actual image file. If you need to upload the file itself (not just its name), use FormData instead:

_results(){
  const fileInput = document.querySelector('input[type="file"]');
  const selectedFile = fileInput.files[0];
  
  if(!selectedFile){
    alert("Please select an image first!");
    return;
  }

  const formData = new FormData();
  formData.append("image", selectedFile);

  fetch("http://0.0.0.0:4000/abc", { // Adjust to your actual upload endpoint
    method: "POST",
    body: formData,
    // Don't set Content-Type here—browser auto-sets the correct multipart/form-data header
  })
  .then(res => res.json())
  .then(res => {
    // Update state with results as before
    const pathSegment = window.location.pathname.split("/")[4];
    this.setState({ res: pathSegment === "gender" ? res.Gender : res.Emotion });
  })
  .catch(err => console.error("Upload error:", err));
}

Step 2: Fix CORS on the Flask Backend

This is the critical part—you need to configure Flask to send the correct CORS headers. The easiest way is using the flask-cors package:

  1. Install the package:
pip install flask-cors
  1. Update your Flask app to enable CORS:
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
# Allow all origins (safe for development; in production, specify your React domain like "http://localhost:3000")
CORS(app)

# Example endpoint matching your React request
@app.route("/abc/<filename>", methods=["POST"])
def analyze_image(filename):
    # Your image processing logic here
    return jsonify({"Gender": "Male", "Emotion": "Happy"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=4000)

If you don’t want to use a package, you can manually set the headers for each route (including handling preflight OPTIONS requests):

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/abc/<filename>", methods=["OPTIONS", "POST"])
def analyze_image(filename):
    # Handle preflight OPTIONS request
    if request.method == "OPTIONS":
        response = jsonify()
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type"
        response.headers["Access-Control-Allow-Methods"] = "POST"
        return response
    
    # Handle POST request logic
    result = {"Gender": "Male", "Emotion": "Happy"}
    response = jsonify(result)
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=4000)

Final Checks

  • Make sure your Flask server is running on http://0.0.0.0:4000 (matches your React request URL)
  • Verify your Flask routes match the URL you’re calling from React
  • For production, replace the wildcard * in Access-Control-Allow-Origin with your actual React domain (e.g., http://your-react-app.com) to avoid security risks

内容的提问来源于stack exchange,提问作者Sai Manikanta Guggilam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:27:11