1

I am trying to create a React Native application. I am using GoogleAutocomplete API on the frontend. From this API I get the coordinates of the place I want. Based on these coordinates I want to sent to the backend where I have the travel advisor API from rapidapi. The backend is in Python and FastAPI. The problem is that it does not display anything. I tried adding some console.logs to see if I get something from the backend but all I get is null. There are 3 variables that I need to get from the frontend to the backend: type, latitude and longitude. The type I get from this code:

   <MenuContainer
              key={"hotels"}
              title="Hotels"
              imageSrc={Hotels}
              type={type}
              setType={setType}
            />
            <MenuContainer
              key={"attractions"}
              title="Attractions"
              imageSrc={Attractions}
              type={type}
              setType={setType}
            />
            <MenuContainer
              key={"restaurants"}
              title="Restaurants"
              imageSrc={Restaurant}
              type={type}
              setType={setType}
            />

The latitude and longitude I get them from the Google Autocomplete API. I need to send these 3 to the backend and get the data back from the backend and use it in another component. As for the reason why I am not using my local server URL, I leave a link to a post on Stackoverflow that explains it. Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet. An emulated device can not see your development machine or other emulator instances on the network. Instead, it sees only that it is connected through Ethernet to a router/firewall. Using 10.0.2.2:8000 reason

Here is the code for the backend:

@app.get("/")
def get_places(type: str, latitude: str, longitude: str):

    url = "https://travel-advisor.p.rapidapi.com/"+type+"/list-by-latlng"


    #querystring = {"latitude": lat, "longitude": lot}
    querystring = {"latitude":latitude,"longitude":longitude}
    
    headers = {
        "X-RapidAPI-Key": "781275f038msh43ccbf90187c7c5p1fa006jsn7c4ba4888a13",
        "X-RapidAPI-Host": "travel-advisor.p.rapidapi.com"
    }

    response = requests.get(url, headers=headers, params=querystring)
    response_json = response.json()

    if response.status_code == 200:
        return response_json['data']
    else:
        raise HTTPException(status_code=response.status_code, detail=response_json)

Here is the code for the frontend:

 const BackendUrl = "http://10.0.2.2:8000/";

  const getPlaces = async () => {
    try {
      if (coordinates) {
        const { latitude, longitude } = coordinates;
        const url = `${BackendUrl}/?type=someType&latitude=${latitude}&longitude=${longitude}`;
        const response = await fetch(url);
        const data = await response.json();

        if (response.ok) {
          console.log("API call successful");
          console.log("Response data:", data);
          // Process the data or assign it to a variable
          return data;
        } else {
          console.log("API call failed");
          console.error("API response error:", data);
          return null;
        }
      }
    } catch (error) {
      console.error("API request error:", error);
      return null;
    }
  };

First I tried using postman to get the request right and I discovered that the URL provided by my local server which is: http://127.0.0.1:8000/, does not work on react native and after some searching I saw that I actually had to change my URL to: http://10.0.2.2:8000/. Next I tried fetching the data after some examples from the internet but without any luck. In postman it's working with the local server URL but in the application I get an error called: Network request failed and API request error.

  • What is the behavior when you try using the swagger UI from `/docs`? Have you tried printing the response to the terminal to pinpoint the issue? – Squarish Jun 04 '23 at 17:42
  • I get response 200. I used fastapi /docs. Here and on postman the I get the same behavior, the API is working with the URL provided by the local server which is: http://127.0.0.1:8000/ – Razvan toth Jun 04 '23 at 17:48
  • Wait so let me get this straight, is your backend hosted on 127.0.0.1:8000 or 10.0.2.2:8000? – Squarish Jun 04 '23 at 17:55
  • My local server is hosted on 12.0.0.1:8000 but I am using an emulator to test my application. It does not work using the local server url and instead is working with 10.0.2.2:8000 – Razvan toth Jun 04 '23 at 18:21
  • Can you [edit] your question and provide more details about your emulator setup and how exactly 10.0.2.2 factors into all this? – Squarish Jun 04 '23 at 18:30
  • Yes, I added a little more information about what I need to do and why I am using 10.0.2.2:8000 instead of my local server URL. I also provided a link to a stackoverflow post explain it in details – Razvan toth Jun 04 '23 at 18:41
  • Oooh I missed the part where you are using react native and not react js. You will need to enable [CORS](https://fastapi.tiangolo.com/tutorial/cors/) for this. – Squarish Jun 04 '23 at 18:47
  • I did enabled CORS: origins = ["http://localhost:3000"] # Replace with your frontend URL app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) – Razvan toth Jun 04 '23 at 18:47
  • I believe you need to host the backend on 0.0.0.0 for it to work and make sure your frontend is coming from localhost:3000 and not another address. – Squarish Jun 04 '23 at 18:54

0 Answers0