vendredi 17 juillet 2020

How to Connect to an API in Your React Native With Expo?

Api

Api is made by laravel in my local environment.

ApiController

public function test(Request $request)
{
    $test = Test::all();
    return response()->json($test, 200);
}

When I get http://127.0.0.1:8000/api/test, it works.


React Native With Expo

When I did expo start, this project has started on http://localhost:19002/

App.js

componentDidMount() {
  axios
    .get('http://127.0.0.1:8000/api/test')
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
      });
}

I got an error:(

Network Error
- node_modules/axios/lib/core/createError.js:15:17 in createError
- node_modules/axios/lib/adapters/xhr.js:80:22 in handleError
- node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:575:10 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

I check this project on Expo Client App on iPhone.

I would appreciate it if you could give me any advice:)



via Chebli Mohamed

1 commentaire:

  1. You cannot use 127.0.0.1 as it will be local to your phone. You have to be on the same network on both the devices firstly and then use the IP address of the machine to make the call.

    RépondreSupprimer