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

React Native用Axios向Flask API传图时网络错误的解决办法

React Native Axios 上传图片到Flask API 报Network Error 解决办法

核心排查与修复步骤

1. 网络地址与跨域配置

  • API地址修正:React Native设备(模拟器/真机)与Flask服务需在同一局域网,禁止使用localhost:
    • Android模拟器用电脑实际IP(如192.168.1.100:5000)或10.0.2.2(映射电脑localhost)
    • iOS模拟器可直接用localhost:5000,真机需用电脑IP
  • Flask跨域开启:Python代码无跨域问题是因为同环境调用,React Native作为客户端必须配置CORS:
    from flask_cors import CORS
    app = Flask(__name__)
    CORS(app)  # 开发环境允许所有跨域,生产环境需指定域名
    

2. FormData 构造规范

React Native的FormData与浏览器实现有差异,需按以下方式构造:

import axios from 'axios';
import { launchImageLibrary } from 'react-native-image-picker';
import { Platform } from 'react-native';

const uploadImage = async () => {
  const pickerResult = await launchImageLibrary({
    mediaType: 'photo',
    quality: 0.8,
  });

  if (!pickerResult.assets?.length) return;

  const formData = new FormData();
  const image = pickerResult.assets[0];
  // 处理Android uri的file://前缀
  const uri = Platform.OS === 'android' ? image.uri.replace('file://', '') : image.uri;

  formData.append('image', {
    uri,
    type: image.type,
    name: image.fileName || 'uploaded_image.jpg',
  });

  try {
    const res = await axios.post('http://你的IP:5000/upload', formData);
    console.log('上传成功:', res.data);
  } catch (err) {
    console.error('错误详情:', err.response || err.message);
  }
};

注意:不要手动设置Content-Type: multipart/form-data,Axios会自动根据FormData生成带正确boundary的请求头,手动设置会导致请求格式错误。

3. Flask 接收逻辑校验

确保Flask端正确解析multipart请求:

from flask import Flask, request
import os

app = Flask(__name__)
CORS(app)

@app.route('/upload', methods=['POST'])
def handle_upload():
    if 'image' not in request.files:
        return '未检测到图片文件', 400
    img_file = request.files['image']
    if not img_file.filename:
        return '未选择文件', 400
    
    # 保存文件到本地(示例)
    os.makedirs('uploads', exist_ok=True)
    img_file.save(os.path.join('uploads', img_file.filename))
    return {'status': 'success', 'filename': img_file.filename}, 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

4. React Native 权限配置

  • Android:在AndroidManifest.xml添加网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
  • iOS:若使用HTTP协议(非HTTPS),需在Info.plist中关闭ATS限制:
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    
    生产环境建议切换为HTTPS,避免ATS限制。

5. 排除Axios自身问题

若以上配置仍报错,用原生fetch测试,确认是否为Axios拦截器或配置导致:

const fetchUpload = async (formData) => {
  const res = await fetch('http://你的IP:5000/upload', {
    method: 'POST',
    body: formData,
  });
  const data = await res.text();
  console.log('Fetch返回:', data);
};

内容的提问来源于stack exchange,提问作者Muhammad Uzair Kabeer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:02:26