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

React Native连接本地Supabase报错TypeError: Network request failed求助

问题:React Native连接本地Supabase出现Network request failed错误

我正尝试将React Native应用连接到本地Supabase开发环境,使用localhost API地址及提供的anon key配置客户端:

const supabaseUrl = 'http://localhost:54321'
const supabaseAnonKey = 'my anon key'

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  auth: {
    storage: new LargeSecureStore(),
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  },
});

但向本地服务器发起任意请求(如查询test表数据、用户注册)时,均出现错误:TypeError: Network request failed:

const { data, error } = await supabase.from("test").select("*");
// 错误信息:'TypeError: Network request failed'

替换为线上Supabase项目的supabaseUrl和supabaseAnonKey时,应用可正常运行;通过终端curl发起相同请求也能返回正确结果:

curl 'http://localhost:54321/rest/v1/test' \
-H "apikey: my anon key" \
-H "Authorization: Bearer my anon key"

# 返回结果:[{"id":1,"created_at":"2023-10-19T09:31:05.307966+00:00"}]

请问该问题的潜在原因是什么?


潜在原因及解决方案

  • localhost的设备解析问题
    React Native运行在模拟器或真机时,localhost指向的是设备自身而非开发电脑:

    • iOS模拟器:若默认localhost无效,可尝试http://127.0.0.1:54321或电脑的局域网IP;
    • Android模拟器:必须替换为http://10.0.2.2:54321(Android模拟器映射主机localhost的特殊地址),或电脑的局域网IP;
    • 真机:直接使用电脑的局域网IP,确保设备和电脑在同一网络下。
  • CORS配置限制
    虽然curl请求不受限制,但React Native的网络请求可能被本地Supabase的CORS规则拦截。检查本地Supabase的config.toml文件,调整CORS允许的来源:

    [api]
    enabled = true
    cors_origin = ["exp://*", "http://localhost:*", "http://*"] # 根据你的RN应用环境调整
    

    修改后重启Supabase本地服务。

  • 平台网络权限/ATS限制

    • Android:确认AndroidManifest.xml中添加了网络权限:
      <uses-permission android:name="android.permission.INTERNET" />
      
    • iOS:由于本地Supabase使用HTTP协议,需在Info.plist中配置允许非HTTPS请求:
      <key>NSAppTransportSecurity</key>
      <dict>
        <key>NSExceptionDomains</key>
        <dict>
          <key>localhost</key>
          <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
          </dict>
        </dict>
      </dict>
      
  • 客户端配置适配问题
    尝试在Supabase客户端配置中显式绑定fetch方法,适配React Native环境:

    export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
      auth: {
        storage: new LargeSecureStore(),
        autoRefreshToken: true,
        persistSession: true,
        detectSessionInUrl: false,
      },
      global: {
        fetch: fetch,
      },
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:16:25