无法在 React Native 中对服务进行 API 调用

Unable to make API call to a service in react native

我是 运行 我本地机器上的一个 NodeJS 服务,其中有一些我创建的 API。我正在尝试使用我的 React 本机应用程序访问这些 API,但出现以下错误:

error [TypeError: Network request failed]

我正在使用 fetch 调用我的服务:

const newUser = fetch('http://localhost:5001/{firebase_service}/us-central1/app/user', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            },
            body: userPayload
        })
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

谁能帮我解封?

我看到您正在尝试从您的应用程序连接到您的本地服务器。但作为 Majid lotfinia pointed out, it is possible that localhost:5001 is pointing to the emulator (or your phone if you're using your physical device) rather than your desktop. Also in many cases react native does not work with http websites, and https is mandatory. So i'd suggest you use Ngrok 进行测试,直到您将服务器移至云端。

问题出在本地主机上,因为本地主机指的是您的模拟器。将 localhost 更改为 10.0.2.2 所以你的 URL 应该是 10.0.2.2:5001{firebase_service}/us-central1/app/user