React Native Axios Network Error when trying to access local JSON server

110 Views Asked by At

I'm trying to access a locally created JSON server from my React Native application. The server is up and running, but when my React Native application tries to access it using Axios, it doesn't return anything, and I'm getting an AxiosError: Network Error. I've tried various URL formats, including using my IP address, localhost, and different port numbers (8000, 3333, 3000), but nothing seems to work. I'm using Expo to run the application on my Android device, and I keep encountering this error.

Here's the code from my api.ts file:

import axios from 'axios';

const api = axios.create({
    baseURL: `http://10.0.2.2:8000`
})

export default api;

And here's part of the code from my index.tsx:

import { useEffect, useState } from 'react';

// ...

useEffect(() => {
    async function fetchEnvironment() {
        
        try {
            const response = await api.get('/plants_environments');
            const { data } = response;
            setEnvironments(data);
          } catch (error) {
            console.error('Error fetching environments:', error);
          }
        
    }

    fetchEnvironment();
    console.log(environments);
})

I've already tried various solutions, like changing the URL format and checking for network connectivity issues, but I'm still stuck with this problem. Any help or guidance would be greatly appreciated. Thank you!

0

There are 0 best solutions below