React Native中Redux Toolkit请求报错:Network Request Failed排查求助
排查React Native + RTK Query调用后端报Network Request Failed的问题
针对你遇到的错误,结合提供的代码,核心排查和修复方向如下:
1. 修复React Native的本地服务地址问题
React Native模拟器/真机中的localhost指向设备自身,而非运行后端服务的电脑,这是最常见的触发原因:
- Android模拟器:将
baseUrl中的localhost替换为10.0.2.2(Android模拟器内置的电脑localhost映射地址) - 真机/通用方案:直接使用电脑的局域网IP地址(比如
192.168.1.105,可通过ipconfig/ifconfig查看) - 修改
apiSlice中的baseUrl:// 示例:替换成自己的局域网IP const baseUrl = 'http://192.168.1.105:8080/'
2. 给后端添加CORS跨域支持
虽然React Native本身对CORS限制较松,但未配置跨域头仍可能导致请求失败:
- 安装cors依赖:
npm install cors - 在后端主文件中引入并启用:
const express = require('express') const topupRoutes = require('./src/router/topupRoutes') const bodyParser = require('body-parser') const cors = require('cors') // 新增 const app = express() const PORT = 8080 app.use(bodyParser.json()) app.use(cors()) // 新增,放在路由之前 app.use('/topup', topupRoutes)
3. 完善前端错误排查逻辑
当前代码仅打印response,无法获取具体错误细节,修改调用代码以输出完整错误信息:
const onCheckout = async () => { const response = await createTopupIntent({ amount: Math.floor(total * 1000), }) // 新增错误判断与打印 if (response.error) { console.error('接口请求失败详情:', response.error) } else { console.log('接口返回数据:', response.data) } }
4. 验证后端接口本身可用性
先排除后端自身问题:
- 使用Postman或curl直接调用后端接口:
curl -X POST http://localhost:8080/topup/intents \ -H "Content-Type: application/json" \ -d '{"amount":1000}' - 如果后端返回错误,检查Stripe密钥是否正确配置、请求参数是否符合Stripe要求(比如amount需为整数)
内容的提问来源于stack exchange,提问作者htm_01
相关产品推荐
相关产品推荐

