Expo Go开发版App无法与Flask API通信求助
Expo Go Android应用无法连接Flask后端API
问题详情
我正以开发模式运行Android Expo Go应用,可通过以下地址访问:
› 选择应用打开项目:http://192.168.0.49:8081/_expo/loading › Metro 等待于 exp://192.168.0.49:8081 › 使用Expo Go(Android)或相机应用(iOS)扫描上方二维码
› Web端等待于 http://localhost:8081
我尝试让该应用与Flask后端API通信,启动Flask的命令及输出如下:
$ flask --app backend run * Serving Flask app 'backend' * Debug mode: off WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000
运行Expo Go应用的移动设备IP:
192.168.0.50
运行Flask服务器的机器IP:
IPv4 Address. . . . . . . . . . . : 192.168.0.49
但从Expo应用向Flask服务器发起GET请求时出现网络错误:
ERROR Test error: [TypeError: Network request failed]
代码片段
Expo TSX测试代码
const testFetch = async () => { try { const response = await fetch('http://192.168.0.49:5000/test'); const data = await response.json(); console.log('Test response data:', data); } catch (error) { console.error('Test error:', error); } }; useEffect(() => { testFetch(); }, []);
Flask后端代码
测试接口
@bp.route('/test', methods=['GET']) def test(): return jsonify({"message": "Test successful"}), 200
CORS配置
import os from flask import Flask from flask_cors import CORS def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) CORS(app, resources={r"/*": {"origins": "*"}}) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from . import home app.register_blueprint(home.bp) return app
已尝试的排查方案
- 在Windows Defender防火墙中开放5000端口的入站和出站流量
- 尝试在手机浏览器中打开Flask端点,无法加载
- 设置Flask应用监听所有地址:
flask --app backend run --host=0.0.0.0 --port=5000 --debug - 尝试在fetch请求中使用https://localhost:5000及实际IP的所有组合
- 尝试在不同网络(移动数据)下运行Flask服务器和Expo Go应用
- 在WSL中通过curl成功调用Flask API:
curl http://192.168.0.49:5000/fetchprogram?programID=test_program - 将端点替换为公开API('https://dog.ceo/api/breeds/list/all')可正常工作
内容的提问来源于stack exchange,提问作者user8188120
相关产品推荐
相关产品推荐

