Tom21487
Tom21487

Reputation: 41

React Native send data to Node.js server with fetch

I'm new to React Native and Node.js so this question may be quite obvious. I have React Native app running from "App.js".

import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default class App extends React.Component 
{
  render() 
  {
    return (
      <View style={styles.container}>
        <Button onPress={this.handlePress} title="Press me" />
      </View>
    );
  }

  handlePress() 
  {
    fetch('http://10.222.22.22:3000/',{
      method: 'POST',
      body: JSON.stringify({
        a: 'hello'
      }),
      headers: {"Content-Type": "application/json"}
    })
    .then(function(response){
    return response.json()
    }).catch(error => console.log(error));
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

(For security reasons, my IP isn't actually 10.222.22.22).

I also have a Node.js server running from "server.js".

var express = require('express');
var app = express();
const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

// Here is where I'm trying to access and log the value of "a"
app.post('/', function (req, res) {
	console.log(req.body.a);
});

app.listen(3000, function() {
  console.log('Listening on port 3000');
});

I'm trying to access the value of "a" (from the fetch body in App.js handlePress()) after it is "sent" to the server. So far, nothing shows up on the console aside from "Listening on port 3000". Any help would be much appreciated, thanks!

Upvotes: 2

Views: 3720

Answers (2)

MANAN
MANAN

Reputation: 823

ngrok allows you to expose a web server running on your local machine to the internet. Ref - Documentation

The setup is pretty simple.

  1. Download ngrok globally from npm by npm i ngrok -g

  2. Open a terminal and run ngrok http 3000 (Because your server is running on port 3000)

  3. You will get a URL something like https://3e8a70f45d9b.ngrok.io (The link will be unique for you)

  4. Run your server on another terminal and run your react native app on yet another terminal

  5. Now change your URL from http://10.222.22.22:3000/ to the link you got from step 3.

Note: Logging in on ngrok.com allows you to have additional time for your sessions unlike the default timeout session which is 2 hours

Upvotes: 1

Calvin
Calvin

Reputation: 599

Try to declare your handlePress as an arrow function.

 handlePress = () => {
    // ... your fetch code
 }

Upvotes: 0

Related Questions