【问题标题】:React Native and require('http')React Native 和 require('http')
【发布时间】:2016-06-16 08:34:55
【问题描述】:

React Native 附带的 node core 似乎不包含 node core http。是否可以在 React Native 中添加和使用?

非常感谢。

【问题讨论】:

标签: react-native


【解决方案1】:

根据 react-native 团队的说法,

对于这种特定情况,您可能希望使用 fetch API 是环境提供的。 React Native 不在内部运行 节点运行时。

fetch 的工作方式与http 类似。以下是如何使用它的简短示例:

// Using fetch to POST

fetch(requestURL, {
  method: 'POST',
  headers: {
   'Accept': 'application/json',
   'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    message: this.state.input,
  })
 })

// Using fetch to GET

fetch(requestURL)
  .then((response) => response.json())
  .then((responseData) => {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(responseData),
      loaded: true,
    });
  })
   .done();

【讨论】:

  • 有趣的是,他们的示例已经过时,不再需要 require('fetch')。据我所知,Fetch func 正在构建中。
【解决方案2】:

我认为你现在被困住了。我的理解是,虽然 React Native 使用 nodejs 来启动和运行,但运行时并不是 实际上 nodejs,这就是为什么你不能只使用require http。

关于来自 nodejs 的 utilrequest,这个已关闭的问题几乎说明了这一点:

https://github.com/facebook/react-native/issues/375

【讨论】:

  • 确实不是节点。老实说,更容易将其视为浏览器,例如使用XMLHttpRequestfetch api。
  • 但是有解决办法吗?
【解决方案3】:

试试这个模块:https://github.com/peter4k/react-native-backbone。它使用主干概念并具有一些http方法。

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 2010-10-12
    • 2016-09-12
    • 2019-02-23
    • 1970-01-01
    • 2018-10-01
    • 2017-01-07
    • 2018-06-25
    相关资源
    最近更新 更多