DevGe
DevGe

Reputation: 1449

How to send the request from react native to express js?

I have concern right now regarding sending the request body from my react native to the back end express JS. Once the button press or click, the logs from my server shows undefined. All get methods are working, except the post method. I read a lot of documents regarding on that.

  1. https://dev.to/saulojoab/how-to-get-data-from-an-mysql-database-in-react-native-53a4
  2. https://reactnativecode.com/fetch-api-tutorial-insert-into-mysql-php/

Imported module:

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

app.use(express.json());

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


var cors = require('cors');

app.use(cors());

Post Method:

app.post('/api/new_readings/', function (req, res) {

  connection.getConnection(function (err, connection) {

    console.log(req.body.name);

   
  });
});

Submit Handler:

 fetch('http://myippppp:3000/api/new_readings/', {
        method: 'POST',
        headers: 
            {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        body: { 
          "name": "x",
          "email": "a",
          "password": "1234"
        }
      })
      .then(response => response.json()) 
      .then(serverResponse => console.warn(serverResponse))

Error:

Error

Hope someone help on this.

Upvotes: 0

Views: 736

Answers (1)

Someone Special
Someone Special

Reputation: 13588

The correct syntax is

Client side

fetch('http://myippppp:3000/api/new_readings/', {
        method: 'POST',
        headers: 
            {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        body: JSON.stringify({ 
          "name": "x",
          "email": "a",
          "password": "1234"
        }) // need to use JSON.stringify
      })
      .then(response => response.json()) 
      .then(serverResponse => console.warn(serverResponse))

Server Side

app.post('/api/new_readings/', function (req, res) {

    console.log(req.body.name);

    return res.json({ ok: true });
});

Upvotes: 1

Related Questions