0

I'm new to React and I try to make Django Rest and react work together.

Btw, my javascript is enabled.

I have a simple view :

class StudentView(generics.ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

I try to fetch it from react with :

  useEffect(() =>{
    fetch("http://127.0.0.1:8000/secretariat/get_student/", {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    })
    .then( resp => resp.json())
    .then( resp => setStudents(resp))
    .catch(error => console.log(error))
    
  }, [])

When i check in browser network the response this is what i have :

enter image description here

I dont think that i have a CORS Header problem but here my CORS settings.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'corsheaders',
    'common_app',
    'rest_framework',
    'rest_framework.authtoken',
    'allauth.account',
    'rest_auth.registration',
    'ldap',
    'rest_auth',
    'simple_history',

]

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

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1'
)
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

I assume i'm doing something wrong but i have no clue.

Thanks

dsimond
  • 103
  • 1
  • 10
  • set CORS_ORIGIN_ALLOW_ALL = True and comment other CORS settings to check if cors is causing the issue – Raghav Sharma Oct 23 '20 at 08:18
  • It seems not to be a matter of CORS. It seems to be something in your web application or in between has enabled JS challenge. It was likely if you were behind something like cloudflare but as you are connecting to your localhost it is probably a proxy or some django app providing with the JS challenge. – Ali Asgari Oct 23 '20 at 08:20
  • Actually it seems to be a CORS issue. I logged the response in the console and i was somehow looping back to my react app. So the message i had was the message from react. Now when i contact my API correctly i have " Access to fetch at 'http://127.0.0.1:8000/secretariat/get_student/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to ..... " – dsimond Oct 23 '20 at 08:34
  • i changed CORS to CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] but my app still reject the request – dsimond Oct 23 '20 at 08:35

1 Answers1

0

Ok well, i don't really know why but i made it work with Axios without changing my CORS Settings at all. If someone know why its working with axios and not with fetch, i would like to know.

So if it happen to someone else here the working code in react using axios :

  axios.get("http://127.0.0.1:8000/secretariat/get_student/")
    .then(response => {
      console.log(response)
      })
    .catch(error => {
      console.log(error);
    })

dsimond
  • 103
  • 1
  • 10