[英]'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尝试按照本教程进行操作,我在 settings.py 中的位置
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. CORS 策略阻止了来自“http://127.0.0.1:8000/engine”的 XMLHttpRequest 策略:没有“Access-Control-Allow-Origin”header请求的资源。
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.感谢 SO 上有很多类似的帖子,但我不明白为什么我会遇到这个问题,而制作教程的人却没有。 This is the rest of my code:这是我的代码的 rest:
models.py模型.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序列化程序.py
from rest_framework import serializers
from .models import Engine
class EngineSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Engine
fields = ('id', 'date')
views.py视图.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网址.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. 'http://localhost:8080' 和 'http://127.0.0.1:8080' 不一样。 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.不过,我不确定端口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.