Как решить ошибку CORS с помощью react и django на aws

У меня есть приложение в продакшене, где www.foo.com является фронтендом на s3, построенным с reactjs и api.foo.com является бэкендом, построенным с django. И фронтенд, и бэкенд находятся на cloudfront.

Теперь, когда я пытаюсь нажать конечную точку create, я получаю следующий результат в консоли.

Access to XMLHttpRequest at 'https ://api.foo.com/create/' from origin 'https ://www.foo.com' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:177 POST https ://api.foo.com/create/ net::ERR_FAILED

react create.js

 ...

 const options = {
        headers: {
            'Content-Type': 'application/json',
            "Access-Control-Allow-Origin": "*", // I have tried to comment this before...
        }
    };

    const handleSubmit = (e) => {
        e.preventDefault();

        console.log("form submitted", fields.name);
    
        axios.post("https ://api.foo.com/create/", fields, options)
        .then(response => {
          console.log("Status", response.status);
          console.log("Data", response.data);
        }).catch((error => {
           console.log("error", error);
        }));
    };

 ...

django settings.py

...
ALLOWED_HOSTS = ["*"] # for the sake of testing


CORS_ORIGIN_WHITELIST = (
    "https ://www.foo.xyz",
)

CORS_ALLOWED_ORIGINS = [
    "https ://www.foo.xyz",
]
...

django views.py

...

@api_view(["POST"])
@parser_classes([JSONParser])
def create(request):
    if request.method == "POST":
        serializer = PersonSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Конфигурация кажется мне правильной, не уверен, что я делаю неправильно

Любая помощь будет очень признательна

Я думаю, что вы не установили django-cors правильно в вашем settings.py. Убедитесь, что вы выполнили следующие дополнительные шаги:

1. Добавить django-cors к приложениям:

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

2. Добавить django-cors в промежуточное программное обеспечение:

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]
Вернуться на верх