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

React Native动态主机名Fetch请求失败问题求助

Fixing "Network request failed" in React Native Fetch with Dynamic Host

Hey there! As a React Native newbie, dealing with network errors can be super frustrating—let's break down what might be causing this issue with your dynamic host Fetch request and how to fix it.

First, let's recap your problem: you're trying to send a POST request to a dynamically generated URL, but keep hitting a TypeError: Network request failed. Let's go through common fixes step by step:

1. Verify Your Request URL is Valid

First things first—make sure the final URL being called is correct. Add a console log right before the fetch to double-check what URL is being generated:

const url = `http://${host}/DashboardApi/public/SignIn`;
console.log('Generated Request URL:', url);
  • Double-check that the host parameter doesn't have typos, extra slashes, or missing parts (like a port number if your server uses one).
  • If you're testing on a simulator:
    • Android simulators can't use localhost directly—replace it with 10.0.2.2 (maps to your computer's localhost) or your computer's local IP address (e.g., 192.168.1.100).
    • iOS simulators can use localhost, but real devices need your computer's local IP.

2. Fix Android's Cleartext HTTP Restriction

Android 9 (API level 28+) blocks plain HTTP requests by default. Since you're using http:// instead of https://, you need to allow cleartext traffic for your server:

  1. Create a file android/app/src/main/res/xml/network_security_config.xml with this content:
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">YOUR_SERVER_IP_OR_HOSTNAME</domain>
        </domain-config>
    </network-security-config>
    
  2. Update your AndroidManifest.xml's <application> tag to reference this config:
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config">
    

3. Tweak Your Fetch Request for Reliability

Your current code is mostly correct, but let's adjust a few things to avoid potential issues:

  • Simplify the headers (you don't need new Headers()—a plain object works fine)
  • Add checks for HTTP status codes to catch server-side errors early
  • Improve error logging to get more context

Here's the revised version of your code:

registerCall = host => {
  const url = `http://${host}/DashboardApi/public/SignIn`;
  console.log('Generated Request URL:', url);
  
  const username = this.state.Usrname;
  fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      username: username,
      password: this.state.password,
    }),
  })
  .then(response => {
    // Check if the response is successful (status code 200-299)
    if (!response.ok) {
      throw new Error(`Server error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(result => {
    console.log('Server response:', result);
    if (result === false) {
      Alert.alert('Wrong Username or Password!');
    } else {
      AsyncStorage.setItem('username', JSON.stringify(result[1]));
      this.props.navigation.navigate('Home');
    }
  })
  .catch(error => {
    console.error('Fetch error details:', error);
    alert('Request failed: ' + error.message);
  });
};

4. Rule Out Server-Side Issues

Before blaming your React Native code, test the endpoint directly using tools like Postman or curl:

  • Send a POST request to the exact URL you're generating, with the same JSON body.
  • If this also fails, the issue is with your server (e.g., it's not running, firewall is blocking requests, or the endpoint path is wrong).

5. Check Device Network Connectivity

  • Ensure your emulator/real device is connected to the same network as your server.
  • For real devices, make sure you're not on a public network that blocks local connections.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:02:41