-2

I am using fetch in react native application to send a post request as:

const data = {
    name: 'name',
    email: 'email'
  }
try{
    var r = await fetch(SEND_INITIAL_DATA, {
      method: 'POST',
      body: JSON.stringify(data),
      headers:{
       'Content-Type': 'application/json'
      }
    });
  }catch(err){
    console.log(err);
  }
  console.log(r);

I am using php in my backend server. but I am unable to access the parameters in php and printing the $_POST is missing body

PHP :

<?php
require 'connect.php';

echo json_decode($_POST); // printing the post

RESPONE

enter image description here

What am I missing ?

Mayank Raj
  • 921
  • 2
  • 12
  • 23

1 Answers1

-1

It's better to use then and catch in fetch for better debugging. example:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Change your code to:

const data = {
    name: 'name',
    email: 'email'
}

    await fetch(SEND_INITIAL_DATA, {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(function(response) {
            return response.json();
        })
        .then(function(myJson) {
            console.warn(myJson);
        });

If you have an error, it will be printed and you can debug it.

Ali Hesari
  • 1,821
  • 5
  • 25
  • 51
  • 1
    It didn't make any difference. Actually, the problem isn't in the REQUEST, it's just that I am not able to access the post parameters in php. – Mayank Raj Jul 30 '18 at 07:52
  • is there any error before the dump ? – Alexandre Painchaud Jul 30 '18 at 07:59
  • "It's better to use then and catch in fetch for better debugging" — That's subjective. Personally, I find `try`/`catch`/`await` to be far more readable. Recommendations for how to debug something are better left to comments rather than answers though. – Quentin Jul 30 '18 at 08:08