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

React Native中fetch请求返回网络错误的技术求助

Troubleshooting React Native Fetch POST Network Errors

Hey there, let's work through that network error you're seeing with your fetch POST request in React Native. I've run into similar issues building mobile apps that mirror web functionality, so here are the most common fixes and checks to narrow down the problem:

1. Fix the Request Body Serialization

First, it looks like your body parameter is incomplete. When sending JSON data via POST, you must serialize your JavaScript object into a JSON string—this is a super common oversight that causes server-side parsing failures (which can manifest as network errors in your app). Update your fetch call like this:

body: JSON.stringify(AdminLoginBindingModel)

Without this step, your server won't understand the request payload, leading to unexpected errors.

2. Verify Network Permissions & Android Cleartext Traffic

  • Android: Make sure your AndroidManifest.xml includes the internet permission (it's easy to forget when setting up a new project):
    <uses-permission android:name="android.permission.INTERNET" />
    
    If your server uses HTTP (not HTTPS), Android 9+ blocks "cleartext" requests by default. To fix this, add android:usesCleartextTraffic="true" to your <application> tag in AndroidManifest.xml:
    <application
      ...
      android:usesCleartextTraffic="true">
    
  • iOS: React Native allows all network requests by default, but double-check that your simulator/device has internet access and can reach the server URL.

3. Validate the Request URL & Server CORS Settings

  • First, test the exact RequestURL in Postman or curl to confirm the server responds correctly. If it fails there, the issue is on the server side, not your app.
  • If the server works in Postman but not your app, check CORS (Cross-Origin Resource Sharing) settings on the server. Make sure it allows requests from your app's context—for mobile apps, this often means permitting requests from your development server (like http://localhost:8081) or your app's bundle ID for production. The server should send headers like Access-Control-Allow-Origin: * (or a specific origin) to permit the request.

4. Add Proper Error Handling to Fetch

Fetch only rejects promises for true network failures (like no internet connection). It will still resolve for HTTP errors (404, 500, etc.), so adding proper error handling will help you see exactly what's going wrong. Update your code to include this:

HttpRequest = (RequestURL, callback) => {
  const AdminLoginBindingModel = { 
    usr: this.state.username, 
    pwd: this.state.password 
  };
  this.setState({ Response: "Performing Fetch..." });

  fetch(RequestURL, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(AdminLoginBindingModel)
  })
  .then(response => {
    // Check if the HTTP status code is successful
    if (!response.ok) {
      throw new Error(`Server returned status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    this.setState({ Response: "Fetch successful!" });
    callback(data);
  })
  .catch(error => {
    this.setState({ Response: `Error: ${error.message}` });
    console.error('Fetch error details:', error); // Log full error for debugging
  });
};

This will log specific errors (like "Network request failed" vs. "Server returned status: 401") so you know whether the issue is network-related or a server-side problem.

5. Check Device/Network Access

  • If using a simulator: Ensure it's connected to the internet (simulators sometimes lose connectivity—try restarting it).
  • If using a physical device: Make sure it's on the same network as your server (if testing locally) or has access to the public internet (if using a production server).

Start with these steps—most fetch network errors in React Native boil down to one of these issues. Once you add the proper error handling, you'll get a clearer picture of exactly what's failing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:40:44