在Django框架中,可以通過以下方法解決跨域問題:
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ALLOWED_ORIGINS = [
'http://example.com',
'https://example.com',
]
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
通過上述配置,可以允許來自http://example.com
和https://example.com
的請求,并允許常見的HTTP方法。
from django.http import HttpResponse
class CorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "http://example.com" # 允許指定的域名訪問
response["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS" # 允許的請求方法
response["Access-Control-Allow-Headers"] = "Content-Type" # 允許的請求頭
return response
然后,在settings.py文件的MIDDLEWARE中添加該中間件:
MIDDLEWARE = [
...
'myapp.middleware.CorsMiddleware',
...
]
通過以上方法,可以解決Django框架中的跨域問題。