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

React Native POST接口调用异常:Postman正常但代码无效怎么修复?

React Native 中调用API失败的修复方案

核心问题及修复步骤

1. 请求体未序列化

你指定了Content-Type: application/json请求头,但直接传入JS对象作为body,fetch不会自动将其转为JSON字符串。必须用JSON.stringify()处理:

body: JSON.stringify(a),

2. 本地地址localhost无法访问

React Native模拟器/真机的localhost指向设备自身,而非你的开发电脑后端。需按场景替换:

  • 安卓模拟器:用10.0.2.2替代localhost(安卓模拟器映射本地电脑的专属地址)
  • iOS模拟器:可直接用localhost,失效时换成电脑局域网IP(如192.168.x.x)
  • 真机:必须使用电脑的局域网IP,确保设备和电脑在同一网络下

修改后的URL示例:

await fetch('http://192.168.1.100/api/test/cetran', {
// 安卓模拟器可写为 http://10.0.2.2/api/test/cetran

3. 响应读取与代码风格问题

  • 同时混用await和.then()写法冗余,建议统一用async/await+try/catch
  • 直接JSON.stringify(response)只能拿到Response对象的元数据,无法获取接口实际返回值,需调用response.json()解析

修复后的完整代码:

const a = {
    ad:'test',
    telefon:'test',
    islem:'test',
    sube:'test',
    saat:'test',
};

async function harrik(){
  try {
    const response = await fetch('http://192.168.1.100/api/test/cetran', {
      method: 'POST',
      headers: {
          'Accept':'application/json',
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(a),
    });
    
    // 解析接口返回的JSON数据
    const data = await response.json();
    console.log('接口返回:', data);
    
    // 检查响应状态码,处理异常情况
    if (!response.ok) {
      throw new Error(`请求失败,状态码: ${response.status}`);
    }
  } catch (e) {
    console.log('请求出错:', e);
  }
}

额外检查项

  • 确认后端API配置了CORS允许跨域请求(开发环境必备)
  • 真机调试时,确保设备和后端服务器在同一局域网内
  • 核对请求方法、参数格式和Postman完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:33:59