React Native调用本地服务器API时出现网络请求失败求助
Hey there, let's work through this network error you're hitting when calling your local API from React Native 0.55.4. I've run into similar issues with older RN versions, so here are actionable steps to fix this:
1. Verify HTTPS vs. HTTP Compatibility
Your code uses https for the API call, but React Native 0.55.4 is strict about self-signed SSL certificates (which most local dev APIs use). This is likely a key culprit:
- Test with HTTP first: Switch your fetch URL to
http://mylocalip:5000/api/tokento rule out SSL certificate issues. - Update platform configs for HTTP:
- On iOS: Add the following to your
Info.plistto bypass ATS restrictions for local dev:<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> - On Android: In
AndroidManifest.xml, addandroid:usesCleartextTraffic="true"to the<application>tag to allow HTTP traffic.
- On iOS: Add the following to your
2. Confirm Local API is Reachable
Before blaming React Native, make sure your API is accessible outside your dev machine:
- Open your phone's browser (connected to the same Wi-Fi as your server) and visit
http://mylocalip:5000/api/token. If you don't get a valid response:- Check if your API server is running and listening on port 5000.
- Ensure your firewall isn't blocking port 5000.
- Confirm your local IP is correct (run
ipconfigon Windows orifconfigon macOS/Linux to get your LAN IP).
3. Fix this Binding in Your Fetch Code
Looking at your code, the this.setState call in the second .then might lose component context (even if this isn't the immediate network issue, it can cause hidden errors):
Rewrite your fetch using arrow functions to preserve this:
fetch('http://mylocalip:5000/api/token') .then(response => { console.log('response : ', response); return response.json(); }) .then(response => { this.setState({ token: response.token }); }) .catch(error => { console.log(error); });
4. Try an Alternative to Fetch
Older React Native versions (like 0.55.4) had occasional bugs with the built-in fetch API. Switch to axios to test if this resolves the issue:
- Install axios:
npm install axios --save - Replace your fetch code with:
axios.get('http://mylocalip:5000/api/token') .then(response => { this.setState({ token: response.data.token }); }) .catch(error => { console.log(error); });
5. Check CORS Settings on Your API Server
Even for local calls, if your API server doesn't allow cross-origin requests from your RN app, it can block the request. In your server code, add a CORS header to allow all origins (safe for development):
// Example for Express.js app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); });
Start with steps 2 and 1 first—they'll quickly rule out basic connectivity and SSL issues. If those don't work, move on to the code and CORS checks.
内容的提问来源于stack exchange,提问作者Avinash

