skip to Main Content

I’m using render to make a simply fullstack app the back end is coded with python and django framework, i’ve deployed the back end and front end using render but i’m still getting the same result which is

Access to fetch at ‘https://api-test-license.onrender.com/licenses’ from origin ‘https://license-frontend.onrender.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.

this is my JS code

const url = 'https://api-test-license.onrender.com/licenses'

export const nuevaLicencia = async license => {

     try {
         await fetch(url, {
             method: 'POST',
             body: JSON.stringify(license),
             headers: {
                 'Content-Type':'application/json'

             }
         });
         window.location.href = 'index.html';
     } catch (error) {
         console.log(error);
     }
 }


 export const obtenerLicencias = async () => {
     try {
         const resultado = await fetch(url);
         const licencias = await resultado.json();
         return licencias;


     } catch (error) {
         console.log(error);
     }
 } 

 export const eliminarLicencia = async id => {
     try {
         await fetch(`${url}/${id}`, {
             method: 'DELETE'
         })
     } catch (error) {
         console.log(error);
     }
 }

 export const obtenerLicencia = async id => {
     try {
         const resultado = await fetch(`${url}/${id}`);
         const licencia = await resultado.json();
    
         return licencia;
     } catch (error) {
         console.log(error);
     }
 }

 export const actualizarLicencia = async licencia => {
     try {
         await fetch(`${url}/${licencia.id}`, {
             method: 'PUT',
             body: JSON.stringify(licencia),
             headers: {
                 'Content-type' : 'application/json'
             }
         });
         window.location.href = 'index.html';
     } catch (error) {
         console.log(error);
     }
 }

and this is my django code in the view file

 from .models import License
 from .serializers import LicenseSerializer
 from rest_framework.response import Response
 from rest_framework import status
 from rest_framework.decorators import api_view, permission_classes
 from rest_framework.permissions import AllowAny

 @api_view(['GET', 'POST'])
 @permission_classes([AllowAny])
 def license_list(request, format=None):



     if request.method == 'POST':
         serializer = LicenseSerializer(data=request.data)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data, status=status.HTTP_201_CREATED)
         else:    
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
     else: 
         licenses = License.objects.all()
         serializer = LicenseSerializer(licenses, many=True)
         return Response(serializer.data, status=status.HTTP_200_OK)


 @api_view(['GET', 'PUT', 'DELETE'])
 @permission_classes([AllowAny])
 def license_detail(request, id, format=None):

     try:
          license_var = License.objects.get(pk=id)
     except License.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
 
     if request.method == 'PUT':
         serializer = LicenseSerializer(license_var, data=request.data)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data)
         else:    
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
     elif request.method == 'DELETE':
         license_var.delete()
         return Response(status=status.HTTP_204_NO_CONTENT)

     else:
         serializer = LicenseSerializer(license_var)
         return Response(serializer.data, status=status.HTTP_200_OK)

It’s just a simple CRUD app but i don’t understand why i’m gettin the same error and i woud like to know how can i solve this and avoid it next time because i’m new with this

2

Answers


  1. I think the request was blocked by the Same-origin policy

    According the code you provided, you fetched at https://api-test-license.onrender.com/licenses from origin https://license-frontend.onrender.com


    For https://api-test-license.onrender.com/licenses

    Protocol:https

    Host:api-test-license.onrender.com


    For https://license-frontend.onrender.com

    Protocol:https

    Host:license-frontend.onrender.com

    So the host between the two is different

    Login or Signup to reply.
  2. I recommend using django-cors-headers.

    https://github.com/adamchainz/django-cors-headers/blob/main/README.rst#setup

    Once you have completed the setup, you can follow the steps below:

    development mode

    # settings.py
    CORS_ALLOW_ALL_ORIGINS = True # add this
    

    online mode

    # settings.py
    CORS_ALLOW_ALL_ORIGINS = False
    CORS_ALLOWED_ORIGINS = [
        'https://license-frontend.onrender.com', # add frontend domain
        ...
    ]
    

    Please do not enable CORS_ALLOW_ALL_ORIGINS in production.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search