React Native 和 require('http')

React Native and require('http')

React Native 附带的节点核心似乎不包含节点核心 http。是否可以在 React Native 中添加和使用它?

非常感谢。

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

关于来自 nodejs 的 utilrequest,这个已关闭的问题说得差不多了:

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

根据 react-native 团队的说法,

For this specific case you'll likely want to use the fetch API which is provided by the environment. React Native does not run inside of the node runtime.

fetchhttp 的工作方式类似。这是一个如何使用它的简短示例:

// 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();

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