关于 ios:React Native:无法连接到开发服务器

React Native: Could not connect to development server

我有一个非常简单的 React Native 项目,我正在尝试开始工作。它是一个 iOS 项目,只需将 RCTRootView 添加到 UIViewController。当我从 Xcode 运行应用程序时,我看到一个带有错误的红色屏幕:

1
2
3
4
5
Could not connect to development server.

Ensure the following:
- Node server is running and available on the same network - run 'npm start' from react-native root
- Node server URL is correctly set in AppDelegate

AppDelegate.h

1
@property (strong, nonatomic) RCTRootView *rootView;

application: didFinishLaunchingWithOptions:

中的 AppDelegate.m

1
2
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
self.rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"HelloReact" initialProperties:nil launchOptions:launchOptions];

ViewController.m 在 viewDidAppear:

1
2
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[self.view addSubview:delegate.rootView];

我不知道如何解决这个问题。我已经尝试了以下所有方法:

  • 启动
  • npm start --reset-cache
  • 删除 node_modules 目录并重新安装
  • 卸载并重新安装 node、watchman、react-native 和 npm
  • 在物理设备和模拟器上尝试过

有没有人发现我的代码有什么问题,或者知道可能是什么问题?我愿意通过电子邮件或电话交谈来解决这个问题。我快绝望了。

我同时遇到了问题。这是我问的另一个问题,其中可能包含一些信息:React Native: Unable to Resolve Module


在 iOS 设备上运行 React Native 应用程序需要指定主机的 IP 地址而不是 localhost:

1
jsCodeLocation = [NSURL URLWithString:@"http://DEV_SERVER_URI:8081/index.ios.bundle?platform=ios&dev=true"];

可以在此答案中找到更具体的说明。


确保您的防火墙没有干扰您。我花了很多时间试图弄清楚为什么这不起作用,我感到很愚蠢,这是我的防火墙???????♂?


这是另一个潜在问题。您也在运行,这是导致此问题的原因。 expo 和 yarn 共享同一个端口,这也会导致问题。我希望这会有所帮助!


确保设备和 Macbook 在同一个 wifi 网络上,并使用闪电 USB 数据线插入。
查看文档了解更多信息


  • 关闭自动打开的 Metro bundler 窗口命令行。
  • 再次运行命令,"react-native run-android"或"react-native run-ios"。