【问题标题】:React Native fetch a local server using a proxyReact Native 使用代理获取本地服务器
【发布时间】:2019-07-17 07:21:37
【问题描述】:

在我的 react native 应用程序中,我试图对我的本地后端服务器执行fetch。在我的package.json 中,我已经输入了"proxy": "http://localhost:3000"

我的抓取看起来像

fetch('/')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log)

它捕捉到一个错误

[TypeError: Network request failed]

当我删除代理并在 fetch 中手动输入地址时,它可以正常工作,并且我的服务器会收到 GET 请求。

fetch('http://localhost:3000')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log)

【问题讨论】:

    标签: reactjs api react-native proxy fetch


    【解决方案1】:

    这里有两点:

    • package.json 中设置proxya feature of create-react-app,它包裹了webpack dev server's proxy。 react-native 使用 Metro 而不是 Webpack 作为打包器,不支持设置本地代理。

    • 与 web 不同,react-native 中的 http 客户端没有当前的host。所以如果你使用fetch('/'),它不会知道向哪个域或IP地址发送请求。

    【讨论】:

      【解决方案2】:

      您好,您可以使用您的网络 IP 地址来使用本地服务器,例如 localhost 更改为您的 IP 地址,您可以调用您的服务器,例如 http://192.xxx.x.xxx:3000

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-26
        • 2020-05-08
        • 2018-09-29
        • 2021-09-08
        • 1970-01-01
        • 2017-07-29
        • 2020-11-21
        • 2012-05-26
        相关资源
        最近更新 更多