1
votes

I have this fetch() method that is sending data from my react-native app to a laravel method

async handleSubmit(){
  var me = this.state.message;
  console.log('this connected',me);
    try {
      let response = await fetch('http://no-tld.example/androidLogin', {
                              method: 'POST',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                              },
                              body: JSON.stringify({
                                  email: '[email protected]',
                                  password: '123456',
                              })
                            });
      //let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
         console.log(response);
      } else {
          //Handle error
          // let error = res;
          // throw error;
      }
    } catch(error) {
        //console.log(res);
    }
  }

I can receive the data using this method

public function androidLogin(){

    $rawData = file_get_contents("php://input");
    $postedValue = json_decode($rawData);
    //parse_str($postedValue, $output);

      return response()->json([
        'name' => $postedValue,
        'route' => $postedValue
            ]);
    }

and attempting to return the just posted data. The posted data looks like this

12:35:07 PM: {"type":"default","status":200,"ok":true,"headers":{"map":{"connection":["Keep-Alive"],"content-length":["54"],"content-type":["application/json"],"set-cookie":["XSRF-TOKEN=eyJpdiI6IlF1NWlLOE9rVCtlUXNpYzBFSTV0c0E9PSIsInZhbHVlIjoiNWtGenprRmJOYTVsc2dQRjNrcmpxZXhWeFZRd1NZSzdiOWFKUUZTZmJJaEN6U0RnbW9uOVZ4bGUrV2ZMYUlIb0NQNHFrT1pCWXB0dnlwTjhPWm56ZWc9PSIsIm1hYyI6IjU3NDJkNWE5M2U4YmIwNTUwNzhkZTM4ZTRlNDc5OTZhNjczYWEyODU0OGNmN2ViNDdkYTM4YjdjY2U1ZWE1ZmYifQ%3D%3D; expires=Fri, 09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/, laravel_session=zqcMrXeuwwGpEsR8Jh2WakDg0cdqLod4QsfMnfcd; expires=Fri, 09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/; HttpOnly"],"access-control-allow-methods":["GET, POST, PUT, DELETE, OPTIONS"],"access-control-allow-origin":["*"],"cache-control":["no-cache, private"],"server":["Apache/2.4.18 (Ubuntu)"],"keep-alive":["timeout=5, max=100"],"date":["Fri, 09 Jun 2017 09:35:07 GMT"]}},"url":"http://no-tld/androidLogin","_bodyInit":"{\"email\":\"[email protected]\",\"password\":\"123456\"}","_bodyText":"{\"email\":\"[email protected]\",\"password\":\"123456\"}"}

I now want to access the returned email from my native-react app.

console.log(response.email); returns null. How can i access the returned email value in react native?

2

2 Answers

1
votes

Try below fetch call,

React-native log-android //Android

or react-native log-ios // IOS

use to see response data or error details

fetch('http://no-tld.example/androidLogin', {
    method: 'POST',
    headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
    body: JSON.stringify({ email: '[email protected]', password: '123456'})
}).then((response) => response.json())
.then((responseData) => {
    console.log("responseData : " +responseData); // fetch response data
}).catch((error) => {
    console.log("error : " +error); // error
});
0
votes

I fixed it this way

async handleSubmit(){
  var me = this.state.message;
  console.log('this connected',me);
    try {
      let response = await fetch('http://198.74.51.225/androidLogin', {
                              method: 'POST',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                              },
                              body: JSON.stringify({
                                  email: '[email protected]',
                                  password: '123456',
                              })
                            });
      let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
        let userData = JSON.parse(res);
         console.log(userData.email);
      } else {
          //Handle error
          // let error = res;
          // throw error;
      }
    } catch(error) {
        //console.log(res);
    }
  }

Just to be sure of the post data returned, you can modify the posted data in the server side and return it using this function

//Android Login
    public function androidLogin(){

    $rawData = file_get_contents("php://input");
    $postedValue = json_decode($rawData,true);
    $token = rand(400,7833);

      return response()->json([
        'email' => $token."_".$postedValue['email'],
        'password' => $postedValue['password']
            ]);
    }

For this to work, i had to also allow cors using this middleware

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

and i used it in my route like this

  //Android
  Route::group(['middleware' => ['cors']], function() {
  Route::post('androidLogin', 'Auth\LoginController@androidLogin');
  });

Hope that helps someone trying to post or get from a react-native app.