1

I'm using React as front end and Django as my backend when i go to the backend URL: localhost:8000 it displays all of the data in JSON and if i use Insomnia/Postman to get and post request it works

However the frontend is not working i get

Access to XMLHttpRequest at 'http://127.0.0.1:8000/cluster/' 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.

I've read other articles on this site, and they all said to add the @csrf_exempt and I already have that and I still get the issues.

settings.py

CORS_ORIGIN_ALLOW = True
CORS_ORIGIN_ALLOW_ALL = True

views.py

@csrf_exempt
def clusterAPI(request, title=''):
    if request.method=='GET':
        clusters = reactUICluster.objects.all()
        clusterSerializer = reactUIClusterSerializer(clusters,many=True)
        return JsonResponse(clusterSerializer.data, safe=False)
    elif request.method=='POST':
        clusterData = JSONParser().parse(request)
        clusterSerializer = reactUIClusterSerializer(data = clusterData)
        if clusterSerializer.is_valid():
            clusterSerializer.save()
            return JsonResponse("Added Successfully", safe=False)
        return JsonResponse("Failed To Add", safe=False)
    elif request.method=='DELETE':
        cluster = reactUICluster.objects.get(title=title)
        cluster.delete()
        return JsonResponse("Deleted Object", safe=False)

axios call inside of my front end

const config = {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"
  }
};
    const axiomCall = async () => {
            console.log("FF");
           const temp = await axios.get("http://127.0.0.1:8000/cluster/", config)
           setRow(temp)
            
            };

Also this article said to use app.use(cors) however since i dont have an app.use() method i cannot do that

import './App.css';
import React, { Component } from "react";
//import axios from "axios";
import RefreshList from './comps/comp1';

function App() {
  
  return (
    <div>
    <RefreshList></RefreshList>
    
    
    </div>
    
  );
}
export default App;

1 Answers1

1

Following these steps worked for me:

  1. Install Django CORS

    pip install django-cors-headers
    
  2. Add it on INSTALLED_APPS (settings.py):

    INSTALLED_APPS = [
        ...
        'corsheaders',
    ]
    
  3. Add it on the top of MIDDLEWARE (settings.py):

    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',
        ...
    ]
    
  4. The CORS variable can be this way (settings.py):

    CORS_ORIGIN_ALLOW_ALL = True
    # or: 
    CORS_ORIGIN_ALLOW_ALL = False
    CORS_ORIGIN_WHITELIST = (
      'http://localhost:3000', # or the reactjs address being used
    )
    
  5. Clear webbrowser cache (Empty Cache and Hard Reload - for chrome) and restart the application.

Helder
  • 61
  • 3