React Native与Flask集成出现Network request failed错误求助
React Native 调用 Flask 后端出现
Network request failed 错误 我是 React Native 和 Flask 新手,正在开发一个将 React Native 中的值传递给 Flask 后端处理的项目,运行时遇到错误:ERROR Error: [TypeError: Network request failed]
原代码
App.js
import React, {Component, useEffect, useState} from 'react'; import { Text, View, SafeAreaView, TextInput, TouchableOpacity, } from 'react-native'; export default function Homescreen() { const [data, setData] = useState(); const [Sl, setSl] = useState(0); const [Sw, setSw] = useState(0); const [Pl, setPl] = useState(0); const [Pw, setPw] = useState(0); const saveData = async () => { const url = `http://localhost:5000/predict`; try { const response = await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'}, Accept: 'application/json', body: JSON.stringify({Sl, Sw, Pl, Pw}), // Pass an object with properties }); if (response.ok) { const result = await response.json(); console.log('Data is added successfully:', result); setData(result); } else { console.error( 'Error fetching data from the server:', response.statusText, ); } } catch (error) { console.error('Error:', error); } }; useEffect(() => { saveData(); // Call the function }, []); // Empty dependency array means this effect runs once on component mount }
app.py
import numpy as np from flask import Flask, request, jsonify, render_template import pickle from urllib.parse import quote as url_quote from flask_cors import CORS # Create flask app flask_app = Flask(__name__) model = pickle.load(open("model.pkl", "rb")) @flask_app.route("/predict", methods=["POST", "GET"]) def predict(): sl = float(request.json()) sw = float(request.json()) pl = float(request.json()) pw = float(request.json()) features = [np.array([sl, sw, pl, pw])] prediction = model.predict(features) return {"prediction": prediction} if __name__ == "__main__": flask_app.run(debug=True)
错误原因及修复方案
1. 网络地址映射问题
React Native 模拟器中的 localhost 不指向电脑本地,需替换为对应地址:
- Android 模拟器:使用
http://10.0.2.2:5000/predict(模拟器内置映射到电脑本地的地址) - iOS 模拟器:可直接用
http://localhost:5000/predict或电脑局域网IP - 真机测试:必须使用电脑的局域网IP(如
http://192.168.x.x:5000/predict),且手机与电脑在同一网络
2. 未启用跨域(CORS)
虽导入了 flask_cors,但未初始化启用,导致跨域请求被拦截,需在创建Flask实例后添加 CORS(flask_app)。
3. Flask 后端数据获取错误
request.json 是字典对象,不是方法,不能加括号调用;且需从字典中提取对应字段,而非重复调用。同时返回数据需用 jsonify 包装为标准JSON响应。
4. 请求时机不合理
useEffect 空依赖数组会在组件挂载时立即调用 saveData,此时输入值为初始0,建议改为点击按钮触发请求。
修改后的代码
App.js
import React, { useState } from 'react'; import { Text, View, SafeAreaView, TextInput, TouchableOpacity, } from 'react-native'; export default function Homescreen() { const [data, setData] = useState(); const [Sl, setSl] = useState(0); const [Sw, setSw] = useState(0); const [Pl, setPl] = useState(0); const [Pw, setPw] = useState(0); const saveData = async () => { // 替换为你的电脑IP或对应模拟器地址 const url = `http://10.0.2.2:5000/predict`; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ Sl, Sw, Pl, Pw }), }); if (response.ok) { const result = await response.json(); console.log('数据提交成功:', result); setData(result); } else { console.error('请求失败:', response.statusText); } } catch (error) { console.error('网络错误:', error); } }; return ( <SafeAreaView style={{ flex: 1, padding: 20 }}> <TextInput value={String(Sl)} onChangeText={(text) => setSl(parseFloat(text) || 0)} placeholder="输入Sl" keyboardType="numeric" style={{ borderBottomWidth: 1, marginBottom: 10, padding: 8 }} /> <TextInput value={String(Sw)} onChangeText={(text) => setSw(parseFloat(text) || 0)} placeholder="输入Sw" keyboardType="numeric" style={{ borderBottomWidth: 1, marginBottom: 10, padding: 8 }} /> <TextInput value={String(Pl)} onChangeText={(text) => setPl(parseFloat(text) || 0)} placeholder="输入Pl" keyboardType="numeric" style={{ borderBottomWidth: 1, marginBottom: 10, padding: 8 }} /> <TextInput value={String(Pw)} onChangeText={(text) => setPw(parseFloat(text) || 0)} placeholder="输入Pw" keyboardType="numeric" style={{ borderBottomWidth: 1, marginBottom: 20, padding: 8 }} /> <TouchableOpacity onPress={saveData} style={{ backgroundColor: '#007AFF', padding: 12, borderRadius: 8 }} > <Text style={{ color: 'white', textAlign: 'center', fontSize: 16 }}>提交预测</Text> </TouchableOpacity> {data && <Text style={{ marginTop: 20, fontSize: 18 }}>预测结果: {data.prediction}</Text>} </SafeAreaView> ); }
app.py
import numpy as np from flask import Flask, request, jsonify import pickle from flask_cors import CORS # 创建Flask应用 flask_app = Flask(__name__) # 启用CORS允许跨域请求 CORS(flask_app) model = pickle.load(open("model.pkl", "rb")) @flask_app.route("/predict", methods=["POST"]) def predict(): # 获取请求体JSON数据 req_data = request.json sl = float(req_data.get('Sl', 0)) sw = float(req_data.get('Sw', 0)) pl = float(req_data.get('Pl', 0)) pw = float(req_data.get('Pw', 0)) features = np.array([[sl, sw, pl, pw]]) prediction = model.predict(features) # 返回标准JSON响应,处理预测结果的格式 return jsonify({ "prediction": prediction[0].item() if hasattr(prediction[0], 'item') else prediction[0] }) if __name__ == "__main__": # 监听所有地址,方便真机访问 flask_app.run(debug=True, host='0.0.0.0')
内容的提问来源于stack exchange,提问作者Afiq Aiman
相关产品推荐
相关产品推荐

