【问题标题】:Network request failed in react-native expo problemreact-native expo 问题中的网络请求失败
【发布时间】:2021-04-21 06:58:19
【问题描述】:

我正在尝试从本地服务器获取数据,但我无法连接本地服务器。我正面临 “网络请求失败”

     const testScreen= async ()=> {
            await fetch("http://192.168.56.1:3000/comments")
            .then((response)=>{
                console.log(response.json())
            })

            .catch((error)=>{
                console.log("sorry")
                console.log(error)
            })
    }

...error..

    Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

【问题讨论】:

  • 在浏览器中打开192.168.56.1:3000/comments,看看服务器是否可达。
  • 需要更多细节,也许您正面临 CORS 问题,您正在通过localhost 和指定 IP 服务器之间的域访问 API
  • 我正在使用 firefox。当我在 web 中运行应用程序时,没有发现 CORS 问题并找到数据。但在移动博览会中再次显示“网络错误”

标签: javascript node.js reactjs react-native


【解决方案1】:

确保服务器正在运行并且位于端口 3000 上。
另外把“testScreen”函数改成这样:

const testScreen = () => {
        fetch("http://192.168.56.1:3000/comments")
        .then(res => res.json())
        .then((response) => {
            console.log(response)
        })
        .catch((error)=>{
            console.log("sorry")
            console.log(error)
        })
}

【讨论】:

  • 我试过了,但同样的问题..“网络请求失败”
【解决方案2】:

这可能与 CORS(跨域资源共享)问题有关。在您的服务器端代码中启用 CORS。

除了 fetch 方法,您还可以使用其他一些库,例如 axios。

axios.get('http://192.168.56.1:3000/comments')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

【讨论】:

  • node_modules\axios\lib\core\createError.js:16:14 in createError 的网络错误
  • 您是否在服务器端启用了 CORS ?
猜你喜欢
  • 2020-07-23
  • 2020-07-04
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2021-11-28
  • 2019-01-06
  • 1970-01-01
相关资源
最近更新 更多