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

React Native使用apisauce无法获取NodeJS后端数据求助

React Native中apisauce请求返回null的解决思路

在Postman和Chrome中可正常获取JSON数据,但在React Native中使用apisauce请求时返回null,相关代码如下:

组件业务代码

const [listings, setListings] = useState([])

useEffect(() => {
  loadListings()
}, []);

const loadListings = async () => {
  const response = await listingsApi.getListings()
  console.log(response.data, "response.data")
  setListings(response.data)
}

apisauce客户端配置

import { create } from "apisauce";

const apiClient = create({
  baseURL: "http://127.0.0.1:9000/api",
});

export default apiClient;

API请求封装

import client from "./client";

const endpoint = "/listings";
const getListings = () => client.get(endpoint);

export default {
  getListings,
};

以下是针对性的解决思路:

  • 修正本地地址映射:React Native模拟器中的127.0.0.1指向模拟器自身,而非你的本地电脑。如果后端服务运行在本地:

    • Android模拟器需将baseURL改为http://10.0.2.2:9000/api
    • iOS模拟器可替换为http://localhost:9000/api或你的电脑局域网IP(如http://192.168.x.x:9000/api)
  • 打印完整响应排查:不要仅输出response.data,打印整个response对象查看详细信息:

    console.log(response, "完整响应详情")
    

    apisauce的响应包含ok(请求是否成功)、status(HTTP状态码)、problem(错误类型,如NETWORK_ERROR、TIMEOUT)等字段,能直接定位问题类型。

  • 添加错误捕获逻辑:在异步请求中加入try/catch,捕获未被apisauce封装的异常:

    const loadListings = async () => {
      try {
        const response = await listingsApi.getListings()
        if (response.ok) {
          setListings(response.data)
        } else {
          console.log("请求失败原因:", response.problem)
        }
      } catch (err) {
        console.log("捕获到异常:", err)
      }
    }
    
  • 检查网络权限与请求头:

    • Android端确保AndroidManifest.xml中添加了网络权限:<uses-permission android:name="android.permission.INTERNET" />
    • 部分后端要求指定Accept请求头,可在apisauce客户端中配置:
      const apiClient = create({
        baseURL: "http://你的正确地址:9000/api",
        headers: { "Accept": "application/json" }
      });
      
  • 验证模拟器网络连通性:在模拟器内置浏览器中直接访问后端API地址,确认能正常获取数据,排除网络连通问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:20:53