My API is providing the expected json response, but I am having an error on my browser when accessing the API I created:
Access to XMLHttpRequest at 'https://tmtg-clone.click/api/courses/most-popular' from origin 'https://fiddle.jshell.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am not sure if there is something wrong with my API code, but here is my views.py
anyways:
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from coursebank_features.api.serializers import *
from coursebank_features.api.variables import *
from common.djangoapps.student.models import CourseEnrollment
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.content.learning_sequences.models import LearningContext
class MostPopularCoursesAPIView(APIView):
def get(self, request):
try:
# Get all course overviews
course_overviews = CourseOverview.objects.exclude(id__in=EXCLUDED_COURSES)
# Get enrollment counts for each course
enrollments = []
for course_overview in course_overviews:
enrollment_end = course_overview.enrollment_end
if enrollment_end is None or enrollment_end > timezone.now():
enrollment_count = CourseEnrollment.objects.filter(
course_id=course_overview.id,
is_active=True
).count()
enrollments.append({
'course_id': course_overview.id,
'course_name': course_overview.display_name,
'enrollment_count': enrollment_count,
})
# Sort the enrollments list by enrollment count in descending order
sorted_enrollments = sorted(enrollments, key=lambda x: x['enrollment_count'], reverse=True)
# Return the top 10 courses with the highest enrollment count
top_enrollments = sorted_enrollments[:10]
# Serialize the enrollment data
serializer = MostPopularCoursesSerializer(top_enrollments, many=True)
# Return the enrollment data as a JSON response
return Response(serializer.data, status=status.HTTP_200_OK)
except CourseOverview.DoesNotExist:
return Response({'error': 'Course not found.'}, status=status.HTTP_404_NOT_FOUND)
I created a plugin that does this:
name: cors
version: 0.1.0
patches:
openedx-lms-common-settings: |
from corsheaders.defaults import default_headers as corsheaders_default_headers
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = corsheaders_default_headers + (
'access-control-allow-origin',
# Add other allowed headers if needed
)
How can I avoid the error: Access to XMLHttpRequest at 'https://tmtg-clone.click/api/courses/most-popular' from origin 'https://fiddle.jshell.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
???
Furthermore, despite knowing the security risks, how can I allow my api to be accessed by any domains?