No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8002' is therefore not allowed access
-
安装
pip install django-cors-headers
-
配置setting.py
INSTALLED_APPS = [
'django.contrib.admin',
·····
'corsheaders',
····
]
MIDDLEWARE = [
······
'corsheaders.middleware.CorsMiddleware', # 按顺序
'django.middleware.common.CommonMiddleware', #按顺序
'django.middleware.csrf.CsrfViewMiddleware', #按顺序
]
# 新增以下配置 #
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# Origin '*' in CORS_ORIGIN_WHITELIST is missing scheme 出现该错误则将其注释掉
CORS_ORIGIN_WHITELIST = (
"*"
)
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
- 其他
- 注意自己的访问路径、django对路径有严格要求
- (corsheaders.E013) Origin '*' in CORS_ORIGIN_WHITELIST is missing scheme 如果出现此错误则将
CORS_ORIGIN_WHITELIST配置注释掉
- csrf_protect:对单个网络请求进行保护 (POST,PUT,DELETE)
from django.views.decorators.csrf import csrf_protect
@csrf_protect # 该请求受到保护
def main(request):
username = request.session.get("has_login",None)
return render(request,"welcome.html",{"username":username})
- csrf_exempt:对单个网络请求取消保护 (POST,PUT,DELETE)
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # 该请求不受保护
def main(request):
username = request.session.get("has_login",None)
return render(request,"welcome.html",{"username":username})
-
关于跨域
image.png
CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。通俗来讲,就是以你的身份,来制造恶意请求。
网友评论