React Native 中的获取请求 post 方法

IT技术 javascript reactjs react-native
2021-04-30 22:58:28

我无法使用 post 方法使其处理 fetch 请求,而 get 其他 api 调用效果很好。这是我的代码:

return fetch(URL_LOCAL + `/addLike`, {
    method: 'post',
    body: JSON.stringify({a: 1})
})
    .then(response => Promise.all([response, response.json()]))
    .catch(err => {
        return Promise.reject(err);
    })

我在获取 URL_LOCAL 之前创建了一个 console.log 并且它返回http://localhost:5000很好

它给了我这个错误:

Network request failed
    at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:15825)
    at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:17902)
    at XMLHttpRequest.setReadyState (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:17657)
    at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:17484)
    at blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:17594
    at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:3480)
    at MessageQueue.__callFunction (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:2386)
    at blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:2156
    at MessageQueue.__guardSafe (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:2348)
    at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/459df9ca-c7b8-48bc-9c45-03d2f1e94f1d:2155)

我在使用 chrome 开发工具查看日志的 android 模拟器上,我使用 node 和 mongodb 作为后端,但我在调用的开头放置了一个日志但没有被触发

编辑:我让它工作,但生产中的 api 与我在 localhost:5000 中使用的代码相同,我不知道 localhost 有什么问题

2个回答

您可以尝试用以下代码替换您的代码:

return fetch(URL_LOCAL + `/addLike`, {
    method: 'post',
    body: JSON.stringify({a: 1})
})
    .then(response => Promise.resolve(response.json()))
    .catch(err => {
        return Promise.reject(err);
    })

我遇到了同样的问题。

我在本地开发,我的 API 在我机器上的 docker 容器中运行。我的 React Native 应用程序由Expo管理,因此我使用与我的机器连接在同一网络上的手机来测试该应用程序。

我做错的是试图将获取请求发送到127.0.0.1:PORT/api/endpointslocalhost:PORT/api/endpoints问题是请求来自我的手机并且应该被发送到 API,如果我们在电话上而不是在 127.0.0.1/localhost 上,而是在我的机器的地址与我的手机在同一网络上。愚蠢吧?

我为解决这个问题所做的是在我的本地网络上获取我机器的当前 IP,与我的手机连接的网络相同,将其用作 API 的 IP 地址。

所以而不是做

fetch('localhost:8000/api/v2/events/upcoming')

我发现 Expo 正在从 192.168.0.110:19000 获取 react 应用程序。这意味着 192.168.0.110 是我机器在网络上的 IP。所以,正确的获取请求是

fetch('192.168.0.110:8000/api/v2/events/upcoming')