如果ssl(https)证书无效,则React Native XMLHttpRequest请求将失败

Art*_*yak 3 javascript ios react-native

当我正在使用无效证书的https服务器执行XMLHttpRequest时,React Native会抛出异常"操作无法完成.(NSURLErrorDomain error -1202.)"

是否可以禁用对React Native XMLHttpRequest的ssl警告/检查?

San*_*son 8

免责声明:此解决方案应该是临时的并记录在案,以便它不会停留在软件的生产阶段,这仅用于开发.

对于iOS,您只需打开您的xcodeproject(在RN中的iOS文件夹中),打开后,转到RCTNetwork.xcodeproj,在该项目中,导航到RCTHTTPRequestHandler.m

在该文件中,您将看到如下所示的行:

 #pragma mark - NSURLSession delegate
Run Code Online (Sandbox Code Playgroud)

在该行之后,添加此功能

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
  completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
Run Code Online (Sandbox Code Playgroud)

瞧,您现在可以在没有有效证书的情况下对API进行不安全的调用.

这应该足够了,但是如果你仍然遇到问题,你可能需要转到项目的info.plist,左键单击它并选择打开为...源代码.

最后加入

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>
Run Code Online (Sandbox Code Playgroud)

所以你的文件看起来像这样

    ...
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string></string>
  <key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)

对于真正的生产就绪解决方案,/sf/answers/2545785231/该解决方案更好