在Django中處理跨域資源共享問題通常有兩種方法:
django-cors-headers
的第三方中間件,可以用來配置CORS(Cross-Origin Resource Sharing)策略。通過安裝django-cors-headers
中間件,并在settings.py
中配置相關參數,可以實現跨域資源共享。首先需要安裝django-cors-headers
:
pip install django-cors-headers
然后在settings.py
中配置中間件:
INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
Access-Control-Allow-Origin
等CORS頭信息,示例代碼如下:from django.http import JsonResponse
def my_view(request):
response = JsonResponse({'message': 'Hello, World!'})
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
response['Access-Control-Allow-Headers'] = 'Content-Type'
return response
這樣就可以在Django中處理跨域資源共享問題了。