【问题标题】:Django CORS Handler is false but not but not rejecting API requestsDjango CORS Handler is false but not but not rejecting API requests
【发布时间】:2022-12-02 00:11:36
【问题描述】:

When I run my Django CORS framework, nothing gets filtered out. The value gets evaluated to false when I insert print statements to the handlers but it's not filtering out requests to my view endpoint. Do I need to make any changes to my view? Am I missing something that will make it reject requests that don't meet the criteria in cors_allow_mysites?

handlers.py

from corsheaders.signals import check_request_enabled

def cors_allow_mysites(sender, request, **kwargs):
   return ("Origin" in request.headers) and (request.headers["Origin"] == 'url.com')

check_request_enabled.connect(cors_allow_mysites)

apps.py

from django.apps import AppConfig

class ApiEndpointConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'api_endpoint'

def ready(self):
    # Makes sure all signal handlers are connected
    from . import handlers  # noqa

__init__.py

default_app_config = "api_endpoint.apps.ApiEndpointConfig"

【问题讨论】:

    标签: django django-rest-framework django-views django-signals django-cors-headers


    【解决方案1】:

    What the check_request_enabled signal does is determinewhether CORS headers (like "Access-Control-Allow-Origin") are added to the response or not, it does not "filter out requests".

    When your cors_allow_mysites function returns True, you should expect to see "Access-Control-Allow-Origin" and other CORS headers in the response, and you should it if it returns False.

    With regards to requests being filtered or not, it all depends on whether those headers are needed or not. If you are on "http://example.com", and you are fetching data from "http://example.com", the CORS headers are not needed, so without the headers, the requests will go through just fine. It's only for cross-origin requests that these headers are needed.

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2023-02-17
      • 2018-12-08
      • 2022-12-02
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 2022-12-01
      • 2022-12-01
      相关资源
      最近更新 更多