python django接口跨域问题和解决 - For POST forms, you need to
Help
Reason given for failure: 拼多多帮助力入口
CSRF cookie not set.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when
CSRF mechanismhas not been used correctly. For POST forms, you need to
ensure:
requestrender{% csrf_token
%}CsrfViewMiddlewarecsrf_protectcsrf_token
DEBUG =
TrueFalse
and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
问题原因
Django 应用在处理 POST 请求时遇到了 CSRF(跨站请求伪造,Cross-Site Request Forgery)验证失败的问题。具体来说,错误信息指出“CSRF cookie not set”,意味着请求中没有找到预期的 CSRF cookie,这是 Django 为了防止跨站请求伪造攻击而采取的安全措施
解决方案
Django 默认并不允许跨域请求,为了允许从 Postman 或其他外部域名发起的 POST 请求,你需要设置 CORS 策略
使用 django-cors-headers
安装
pip install django-cors-headers
注意和 django 的版本对应,不同版本的 django-cors-headers 所依赖的 django 版本不同,具体可以参考:https://pypi.org/project/django-cors-headers/3.0.0/
注册
将 corsheaders 添加到 INSTALLED_APPS 列表中。 添加 CORS 中间件到中间件列表中,并确保它位于其他中间件之前,以便它可以最早处理 CORS 头部。 可以全局允许所有来源,或者指定允许的来源列表。
# settings.py
INSTALLED_APPS = [
# ...
'corsheaders',
# ...
]
MIDDLEWARE = [
# CORS Headers middleware should be placed as high as possible
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
# ...
]
CORS_ORIGIN_ALLOW_ALL = True # 这将允许所有来源的请求。在生产环境中,你可能需要更严格的控制,比如列出具体的允许来源。
# 或者,你可以指定允许的源列表:
# CORS_ALLOWED_ORIGINS = [
# "http://localhost:3000",
# "https://example.com",
# ]
注意的就是 cors-headers 的中间件CorsMiddleware 在注册时必须放在 django-common 中间件的前一个。
但是这种方式我最终没成功,目前原因没找到。
使用装饰器 @csrf_exempt
导入
from django.views.decorators.csrf import csrf_exempt
使用
@csrf_exempt
def notify_success(request):
# 你可以根据需要处理请求数据,这里简化处理直接返回成功信息
return HttpResponse('success')
@csrf_exempt
def notify_failure(request):
# 同样,这里简化处理直接返回失败信息
return HttpResponse("failure")
使用该方式成功,apifox 再发起请求后,请求成功,跨域问题不存在。
精彩内容