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

TypeScript CSV文件上传至后端时遭遇Nginx 500内部服务器错误

问题:React上传Binance CSV到Flask后端报500内部服务器错误

前端代码(TypeScript React组件)

import React, { useContext, useState } from "react";
import Context from "./Context";

const BinanceCSVUpload = ({ handleClose }: { handleClose: any }) => {
  const { dispatch } = useContext(Context);
  const [file, setFile] = useState<File | null>(null);
  const [formErrorState, setFormErrorState] = useState("");

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setFile(e.target.files[0]);
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!file) {
      alert("Please select a CSV file to upload.");
      return;
    }

    console.log(file);
    const formData = new FormData();
    formData.append("file", file);

    // Log the contents of formData
    formData.forEach((value, key) => {
      console.log(key, value);
    });

    try {
      const response = await fetch(
        "/api/accounts/csv_upload",
        {
          // Adjust URL if needed
          method: "POST",
          body: formData,
        }
      );

      if (!response.ok) {
        const text = await response.text(); // Read the response body
        console.error("Upload failed:", response.statusText, text);
        setFormErrorState("SUBMIT_FAILED");
        return;
      }
      const data = await response.text();
      alert(data);

      dispatch({
        type: "SET_STATE",
        state: {
          refreshBinanceCSV: true,
        },
      });

      if (handleClose) {
        handleClose();
      }
    } catch (error) {
      alert("An error occurred: " + error);
    }
  };

  return (
    <form onSubmit={handleSubmit} encType="multipart/form-data">
      <label>
        Upload Binance CSV File:
        <input
          type="file"
          name="file"
          accept=".csv"
          onChange={handleFileChange}
          required
        />
      </label>
      <button type="submit">Upload</button>
    </form>
  );
};

export default BinanceCSVUpload;

后端Flask接口

@app.route("/accounts/csv_upload", methods=["POST"])

错误信息

前端收到:

POST http://localhost/api/accounts/csv_upload 500 (Internal Server Error)

错误弹窗显示Nginx版本及500错误,且Flask后端无日志输出,怀疑前端或Nginx层面存在问题。

Nginx配置文件

events {
    worker_connections  1024;
}

http {

map $http_upgrade $connection_upgrade {
      default upgrade;
      '' close;
  }

  upstream grafana {
       server localhost:3000;
  }

server {
  
    
  listen 80;
  root /usr/share/nginx/html;
  index index.html index.htm;
  
  location /api/ {
      proxy_pass http://localhost:8000/;
      proxy_set_header Host $http_host;
      proxy_read_timeout 300s;
      client_max_body_size 100M;
      proxy_buffering off;
  }
  location / {
      proxy_pass http://localhost:5000/;
      proxy_set_header Host $http_host;
      proxy_read_timeout 300s;
      client_max_body_size 100M;
      proxy_buffering off;
}

排查建议与解决方案

1. 验证Nginx路由转发正确性

前端请求/api/accounts/csv_upload被Nginx转发到http://localhost:8000/accounts/csv_upload,需确认Flask服务是否运行在8000端口:

  • 若Flask实际运行在5000端口,需将location /api/下的proxy_pass改为http://localhost:5000/;
  • 直接访问http://localhost:8000/accounts/csv_upload(用POST方法携带FormData),测试服务是否能正常响应,排除转发路径错误。

2. 查看Nginx错误日志

请求未到达Flask的概率极高,查看Nginx错误日志(默认路径/var/log/nginx/error.log),可获取转发失败、端口不通、配置错误等具体原因。

3. 检查Nginx配置有效性

执行以下命令验证配置文件语法并重载:

sudo nginx -t
sudo nginx -s reload

避免因配置未生效导致的转发异常。

4. 确认请求是否正确发送

在浏览器开发者工具的Network面板中:

  • 检查请求的Content-Type是否为multipart/form-data; boundary=xxx(FormData自动生成,无需手动设置);
  • 确认请求参数中是否包含上传的文件数据。

5. 排查Flask服务状态

若上述步骤确认转发正常,需检查Flask服务是否正常启动、端口是否被占用,以及后端代码是否正确处理文件上传(如使用request.files.get('file')获取文件)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:18:09