React Native,iOS 15,提取:TypeError:网络请求失败

发布于 2025-01-18 15:55:27 字数 3177 浏览 2 评论 0原文

我在 React Native 中遇到了这个问题(在 iOS 15.4 上):

TypeError: Network request failed
    at fetch.umd.js:535:18
    at JSTimers.js:214:18
    at _callTimer (JSTimers.js:112:7)
    at Object.callTimers (JSTimers.js:357:7)
    at MessageQueue.__callFunction (MessageQueue.js:419:27)
    at MessageQueue.js:116:12
    at MessageQueue.__guard (MessageQueue.js:370:9)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:115:10)
    at debuggerWorker.js:69:58

...并且我看到了许多修改 ios/[APP_NAME]/Info.plist 文件以允许 HTTP 请求的建议。不幸的是,它们都不适合我。我不确定我是否遗漏了任何步骤或出了什么问题。

首先,域是 api.localhost:84 这是我当前的配置片段:

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>

我还尝试了许多其他变体,例如:

  1. 将域更改为 api.localhost< /code> 或 api.localhost:84
  2. 添加 NSExceptionMinimumTLSVersionTLSv1.1
  3. 设置 NSExceptionDomains 之外的异常(适用于每个域),
  4. 使用 NSTemporaryExceptionAllowsInsecureHTTPLoads
  5. 使用 NSAllowsArbitraryLoads...

我想我尝试了所有解决方案,我在 StackOverflow 上找到了它们,但它们都不起作用。每次我进行更改时,我也会从模拟器中卸载应用程序并重新构建它。我还发现了一些使用 IP(而不是 localhost)的建议,但它说它适用于 Android,而且我知道,localhost 曾经为我工作过iOS。但有一天它停止工作了。

我缺少任何步骤吗?或者最近是否有任何变化,需要以不同的方式做事?

我一无所知......当我用谷歌搜索错误时,所有链接都已经是紫色的。我什至尝试了谷歌结果的第二页。什么都不起作用。

PS:这是我的JS代码:

class ApiConnector {

    static async post(api, path, body) {

        try {
            let response = await fetch(api.baseUrl + path, {
                method: "POST",
                headers: this.getHeaders(api.app.state.auth),
                body: JSON.stringify(body),
            });

            if (response.status >= 200 && response.status < 300) {

                // Success
                return response.json();

            } else {
                api.app.alert('"' + path + '" responded with ' + response.status);
            }

        } catch (e) {
            console.log(e);
            api.app.alert('Request error ('+e.message+').');
        }

        return false;
    }


    static getHeaders(auth: {login: string, password: string}): Headers {
        let headers = new Headers();

        if (auth.login && auth.password) {
            let base64 = require('base-64');
            headers.append(
                'Authorization',
                'Basic ' + base64.encode(auth.login+':'+auth.password)
            );
        }

        headers.append('Accept','application/json');
        headers.append('Content-Type','application/json');

        return headers;
    }
}

I'm having this problem with fetch in React Native (on iOS 15.4):

TypeError: Network request failed
    at fetch.umd.js:535:18
    at JSTimers.js:214:18
    at _callTimer (JSTimers.js:112:7)
    at Object.callTimers (JSTimers.js:357:7)
    at MessageQueue.__callFunction (MessageQueue.js:419:27)
    at MessageQueue.js:116:12
    at MessageQueue.__guard (MessageQueue.js:370:9)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:115:10)
    at debuggerWorker.js:69:58

...and I have seen many recommendations to modify the ios/[APP_NAME]/Info.plist file to allow HTTP requests. Unfortunately, none of them work for me. And I am not sure if I'm missing any steps or what's wrong.

So first, the domain is api.localhost:84 and this is my current snippet of the configuration:

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>

I have also tried many other variations, such as:

  1. changing the domain to api.localhost or api.localhost:84,
  2. adding <key>NSExceptionMinimumTLSVersion</key><string>TLSv1.1</string>,
  3. setting the Exception out of the NSExceptionDomains (to apply to every domain),
  4. using <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key><true/>,
  5. using <key>NSAllowsArbitraryLoads</key><true/>...

I think I tried every solution, that I have found on StackOverflow and none of them work. Every time I make a change, I also uninstall the app from the simulator and rebuild it. I have also found some advice to use the IP (instead of localhost), but it said that it applies to Android and I know, that localhost used to work for me on iOS. But one day it stopped working.

Is there any step that I'm missing? Or was there any change recently, which would require doing things differently?

I'm clueless... When I google the error, all the links are already purple. I even tried the second page of google results. Nothing works.

PS: This is my JS code:

class ApiConnector {

    static async post(api, path, body) {

        try {
            let response = await fetch(api.baseUrl + path, {
                method: "POST",
                headers: this.getHeaders(api.app.state.auth),
                body: JSON.stringify(body),
            });

            if (response.status >= 200 && response.status < 300) {

                // Success
                return response.json();

            } else {
                api.app.alert('"' + path + '" responded with ' + response.status);
            }

        } catch (e) {
            console.log(e);
            api.app.alert('Request error ('+e.message+').');
        }

        return false;
    }


    static getHeaders(auth: {login: string, password: string}): Headers {
        let headers = new Headers();

        if (auth.login && auth.password) {
            let base64 = require('base-64');
            headers.append(
                'Authorization',
                'Basic ' + base64.encode(auth.login+':'+auth.password)
            );
        }

        headers.append('Accept','application/json');
        headers.append('Content-Type','application/json');

        return headers;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文