AxiosError: Сетевая ошибка при вызове API из react native в django rest framework

Я запускаю свое приложение на своем андроид-устройстве и не использую никаких эмуляторов. Из postman я могу вызывать API, определенные в django rest framework, однако при вызове их с фронт-энда я получаю следующую ошибку: AxiosError: Network Error

Settings.py:

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cadence',
    'rest_framework_simplejwt',
    'rest_framework',
    'corsheaders',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': ( 
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ) 
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

CORS_ALLOW_ALL_ORIGINS = True

SpitifyViews.py:

class SpotifyViews(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def create_spotify_token(request):
        try:
            url = 'https://accounts.spotify.com/api/token'
            headers = {
                "content-type": "application/x-www-form-urlencoded"
            }
            data = {
                "grant_type": "client_credentials",
                "client_id": "{my client id}",
                "client_secret": "{my client secret}"
            }

            encoded_data = urlencode(data)
            response = requests.post(url, headers=headers, data=encoded_data)

            if response.status_code == 200:
               return JsonResponse(response.json())
            else:
                return JsonResponse({"error": "Failed to get Spotify token"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
        except Exception as error:
            return JsonResponse({"error": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

JS Code:

axios.defaults.baseURL = "http://localhost:8000/";

export const sendRequest = async (method, endpoint, body) => {
    const response = await axios.request({
        method: method,
        url: endpoint,
        data: body,
        headers: {
            // Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
    });

    if (response.status === 401) {
        // do somethinhg
    }

    return response;
};
const handleSignUp = async () =>{
  console.log("signed up")
  router.push("/login")
  if(!info.email || !info.username || !info.password){
    Alert.alert("Error", "All fields are required")
    return
  }
  setIsSubmitting(true)
  console.log(info)
  try{
    const response = await sendRequest(requestMehods.POST, "cadence/api/user/register/", {
      ...info,
    });
    console.log("response")
    if (response.data.status === "success") {
      // do somethinhg
      router.push("/registration")
    }
  } catch (error){
    console.log(error)
  } finally {
    setIsSubmitting(false)
  }
};

Есть идеи, в чем может быть причина?

Вернуться на верх