'Access-Control-Allow-Origin' issue even though I've set up the settings.py correctly?
amateur developer here. Trying to follow this tutorial, where in the settings.py I have
CORS_ALLOWED_ORIGINS = ['http://localhost:8080']
as per the video.
However, when I try to access the server from my front-end, I get the error
Access to XMLHttpRequest at 'http://127.0.0.1:8000/engine' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Appreciate there are many similar posts on SO, but I couldn't understand why I'm having this issue whereas the guy who made the tutorial does not. This is the rest of my code:
models.py
from django.db import models
from django.utils import timezone
import datetime
class Engine(models.Model):
date = models.DateField(default=datetime.datetime(2024,1,1))
serializers.py
from rest_framework import serializers
from .models import Engine
class EngineSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Engine
fields = ('id', 'date')
views.py
from django.shortcuts import render
from .models import Engine
from .serializers import EngineSerializer
from rest_framework import viewsets
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
class EngineViewSet(viewsets.ModelViewSet):
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Engine.objects.all()
serializer_class = EngineSerializer
urls.py
from django.contrib import admin
from django.urls import path, include
from backend_app.views import EngineViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('engine', EngineViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls))
]
'http://localhost:8080' and 'http://127.0.0.1:8080' are not the same. They may point to exactly the same code and functions, but they are different for such matter.
Put both options inside the list:
CORS_ALLOWED_ORIGINS = ['http://localhost:8080', 'http://127.0.0.1:8000']
I'm not sure about ports, though.
Some more help is to found HERE.