7

The node core shipped with React Native does not seem to include node core http. Is it possible to add it and use at all within React Native?

Many Thanks in Advance.

4

3 回答 3

17

根据 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();

于 2015-04-04T23:20:47.793 回答
7

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

这个已关闭的问题几乎说明了关于nodejsutilrequest来自 nodejs 的内容:

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

于 2015-03-31T15:33:09.470 回答
0

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

于 2015-10-14T05:48:04.237 回答