React Native无法连接localhost:iOS启动代码运行异常求助
Hey there, let's troubleshoot this React Native iOS connection issue step by step— I’ve run into this exact headache before, so here are some practical fixes that usually get things working:
1. Replace localhost with your computer's actual IP address
Sometimes the iOS simulator doesn’t resolve localhost to your computer correctly. Try using your machine’s local IP instead:
- On Mac: Run
ifconfig | grep inetin Terminal and grab theinetaddress underen0(usually something like192.168.1.100). - On Windows: Run
ipconfigand get the IPv4 address for your active network adapter. - Update your code to use this IP:
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://192.168.1.100:8081/index.bundle?platform=ios"]; - Test if you can access
http://your-ip:8081directly in the simulator’s Safari— if you see a wall of JS code, the Metro server is reachable; if not, move to the next step.
2. Force Metro to listen on all network interfaces
By default, Metro might only bind to localhost, which can block simulator access. Start Metro with this command:
npm start -- --host 0.0.0.0
Or make this permanent by updating your package.json start script:
"scripts": { "start": "react-native start --host 0.0.0.0" }
Now npm start will automatically listen on all available IPs.
3. Double-check your ATS disable configuration
Even if you think you’ve disabled ATS, it’s easy to misconfigure it. Verify your Info.plist has this exact setup:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
Avoid mixing this with NSExceptionDomains settings unless you specifically need them— they can override the arbitrary loads permission.
4. Reset simulator cache and React Native cache
Cached data can cause weird connection glitches:
- Erase simulator data: Go to simulator menu >
Hardware > Erase All Content and Settings, then restart the simulator. - Clear React Native cache: Run this in Terminal:
npm start -- --reset-cache
5. Check for port conflicts or firewall blocks
- Verify port 8081 isn’t occupied by another app: Run
lsof -i :8081in Terminal. If results show a process, kill it withkill -9 <PID>(replace<PID>with the process ID from the output). - Temporarily disable your computer’s firewall to rule out blocking— if it works after disabling, add an exception for port 8081.
6. Fallback to a local bundle (to isolate the issue)
If all network fixes fail, test with a local bundle to confirm it’s a network problem:
- Generate the local bundle:
react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios - Update your code to load the local file:
NSURL *jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; - Recompile and run— if this works, the issue is definitely network-related, so circle back to the earlier steps.
内容的提问来源于stack exchange,提问作者meisel

