skip to Main Content

Post installing android studio & react native cli, I am trying fetch functionality for the first time. I tried the POST API as given on Facebook URL as follows:

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})
.then((response) => response.json())  // Here is the error saying, response not defined.

Problem: It seems, the request itself is not being posted at the endpoint URL, at all. So get error as “response not defined” at the line where response is fetch and manipulated. Thorough chrome postman tested the URL which works fine, but from react native code fetch is not working. Is it like anything else needs to be installed or configured to make fetch API work properly. Kindly help/suggest.

Thanks in advance
~Vinay

3

Answers


  1. Try below fetch call,

    React-native log-android //Android

    or react-native log-ios // IOS

    use to see response data or error details

    fetch('https://mywebsite.com/endpoint/', {
        method: 'POST',
        headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
        body: JSON.stringify({ firstParam: 'yourValue', secondParam: 'yourOtherValue'})
    }).then((response) => response.json())
    .then((responseData) => {
        console.log("responseData : " +responseData);
    }).catch((error) => {
        console.log("error : " +error);
    });
    
    Login or Signup to reply.
  2. The problem is JSON.stringify.
    Use FormData instead. No need to install, it’s not 3rd party.

    import FormData from 'FormData';
    
    var formData = new FormData();
    
    formData.append('username', 'Andy');
    
    ...
    
    { 
      ... 
      body: formData 
      ... 
    }
    
    Login or Signup to reply.
  3. Step1: open /<Project Folder>/android/app/src/main/AndroidManifest.xml.
    ( do not get confused because there will be two AndroidManifest.xml)

    Step2: Add the line

    android:usesCleartextTraffic="true"

    (under "/manifest/application)

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search