Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native and require('http')

Tags:

react-native

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.

like image 325
NotoriousDMC Avatar asked Mar 31 '15 14:03

NotoriousDMC


2 Answers

According to the react-native team,

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.

fetch works similarly to http. Here is a short example of how to use it:

// 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();
like image 187
Jonathan Huang Avatar answered Oct 05 '22 10:10

Jonathan Huang


I think you're stuck at the moment. My understanding is that while React Native uses nodejs to get up and running, the runtime isn't actually nodejs, which is why you can't just require http.

This closed issue says pretty much that, with regards to util and request from nodejs:

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

like image 34
Colin Ramsay Avatar answered Oct 05 '22 10:10

Colin Ramsay