【问题标题】:React native fetch throw exception Network request fail on android反应本机获取抛出异常网络请求在android上失败
【发布时间】:2019-05-31 09:28:59
【问题描述】:

我正在使用 fetch 进行 API 调用并获取 JSON 响应。
但它在 android 上抛出异常但在 iOS 上工作。

fetch(url, {
    method: requestMethod,
    body: formData,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
})
.then((response) => {
    return response.json();
})
.then((responseJson) => {
    console.log("Response JSON :- " + JSON.stringify(responseJson));
})
.catch((error) => {
    console.log("Exception :- " + error);
})

错误:-

“TypeError:网络请求失败。
在 XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:24140:18)。

at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:28784:27).

at XMLHttpRequest.setReadyState (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:28537:20).

at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:28364:16).

at blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:28474:47.

at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:3280:37).

at MessageQueue.__callFunction (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:2577:44).

at blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:2334:17.

at MessageQueue.__guard (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:2531:13).

at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/1a80ef13-8ce9-4c75-a477-e214c5fd3ff2:2333:14)".

【问题讨论】:

    标签: android reactjs react-native


    【解决方案1】:

    在 url 中使用服务器的 IP 地址而不是 localhost:8081。

    【讨论】:

    • 你不需要加上:8080和ip,只需使用your设备ip/服务路径。
    • 删除“headers: { Accept: 'application/json', 'Content-Type': 'application/json', }”后问题解决了
    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 2019-09-16
    • 2019-03-19
    • 2022-10-13
    • 2021-11-28
    • 2018-03-01
    • 2019-02-09
    • 2020-07-05
    相关资源
    最近更新 更多