我可以使用Postman访问我的Django REST api,但当我在Nuxt上运行它时,我会得到;已被CORS策略阻止:请求的资源上不存在"Access Control Allow Origin"标头">
让我知道你想看到我代码的哪些部分,我很乐意分享。
这是我的设置.py文件
DEBUG = True
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'rest_framework',
'corsheaders',
'core',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # add this
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
'http://127.0.0.1:8000'
)
这肯定是后端的问题,我指的是Django。
因此,Django端的属性值应该是这样的。CORS_ALLOW_ALL_ORIGINS=True
设置CORS_ALLOW_ALL_ORIGINS
值后,还需要设置ALLOWED_HOSTS
的值。例如ALLOWED_HOSTS=['*']
请查看以下链接。
https://pypi.org/project/django-cors-headers/
https://dzone.com/articles/how-to-fix-django-cors-error