跨域问题:Access to XMLHttpRequest at......
前端代码报错,如图:
1、因本地不支持跨域,需要安装下【允许跨域的app】
pip install django-cors-headers
2、回到Django项目中进入setting.py
INSTALLED_APPS:
# 我们创建了哪些子项目要在这里添加,不然如数据库的类不会帮创建 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sky', 'user', 'corsheaders' # 允许跨域的 ]
MIDDLEWARE:
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware' # 允许跨域的中间件,需要安装:pip install django-cors-headers # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'sky.middle_wares.TestMiddleWare', # 以下是自定义中间件 'user.middle_wares.PutMethodMiddleware', 'user.middle_wares.SessionMiddleware', # 报错处理 'user.middle_wares.ExceptionMiddleware' # 验证token ]
配上以下2个参数:
CORS_ORIGIN_ALLOW_ALL = True # 加上这个允许所有跨域 CORS_ALLOW_HEADERS = '*'
本文来自博客园,作者:他还在坚持嘛,转载请注明原文链接:他还在坚持嘛 https://www.cnblogs.com/brf-test/p/17294475.html