通过发出跨端口请求,您正在破坏浏览器同源策略 https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy。这样做是出于安全原因。
浏览器还允许您通过设置称为CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS。基本上,您必须返回一个名为Access-Control-Allow-Origin
从您的后端告诉浏览器您信任传入的源。
欲了解更多信息,您可以阅读链接页面。
在开发过程中,我使用这些设置来监听跨域请求:
# It may be a good idea to use appropriate values during production
ALLOWED_HOSTS = ['*']
CSRF_TRUSTED_ORIGINS = ['*'] # if you're serving your frontend
# and backend under same domain and port
# during production, then you can remove
# this.
然后我还有一个中间件,它在每个 HTTP 请求上注入所需的 CORS 标头。
如果您在同一域和端口上为前端和后端提供服务,则不需要这样做。所以在生产过程中最好不要使用这个中间件。如果必须,请使用适当的值。
我将此代码保存在一个名为的文件中middleware.py
并将此文件保存在与我的目录相同的目录中settings.py
file.
# project_name/project_name/middleware.py
from django.http import HttpResponse
from django.conf import settings
CORS_ALLOW_ORIGIN = getattr(settings, 'CORS_ALLOW_ORIGIN', '*')
CORS_ALLOW_METHODS = getattr(settings, 'CORS_ALLOW_METHODS', ['POST', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'])
CORS_ALLOW_HEADERS = getattr(settings, 'CORS_ALLOW_HEADERS', ['content-type', 'authorization'])
CORS_ALLOW_CREDENTIALS = getattr(settings, 'CORS_ALLOW_CREDENTIALS', True)
CORS_EXPOSE_HEADERS = getattr(settings, 'CORS_EXPOSE_HEADERS', ['content-type', 'location'])
class CorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def set_headers(self, response):
response['Access-Control-Allow-Origin'] = CORS_ALLOW_ORIGIN
response['Access-Control-Allow-Methods'] = ','.join(CORS_ALLOW_METHODS)
response['Access-Control-Allow-Headers'] = ','.join(CORS_ALLOW_HEADERS)
response['Access-Control-Allow-Credentials'] = 'true' if CORS_ALLOW_CREDENTIALS else 'false'
response['Access-Control-Expose-Headers'] = ','.join(CORS_EXPOSE_HEADERS)
return response
def __call__(self, request):
response = self.get_response(request)
response = self.set_headers(response)
return response
最后,更改一些设置来告诉 Django 使用这个中间件:
MIDDLEWARE = [
# ... other middlewares ...
'project_name.middleware.CorsMiddleware',
]
重要的:如果您在同一域和端口下为前端和后端提供服务,则在生产中可能不需要此答案中的任何代码。但更多地了解 CORS 仍然是一个好主意。