【问题标题】:Django REST API and Nuxt.js - (CORS error in Nuxt)Django REST API 和 Nuxt.js -(Nuxt 中的 CORS 错误)
【发布时间】:2020-12-27 00:12:01
【问题描述】:

我可以使用 Postman 访问我的 Django REST api,但是当我在 Nuxt 上运行它时,我得到“已被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’标头。”

让我知道您希望看到我的代码的哪些部分,我很乐意分享。

这是我的 settings.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'

)

【问题讨论】:

    标签: python django cors nuxt.js


    【解决方案1】:

    这绝对是后端的问题,我是说 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

    【讨论】:

    • 我现在试过了。请参见上面的代码。这是我的确切错误:(索引):1 从源 '192.168.0.11:3000' 访问 XMLHttpRequest 在 '192.168.0.11:3000' 已被 CORS 策略阻止:请求中不存在 'Access-Control-Allow-Origin' 标头资源。
    • GET 127.0.0.1:8000/api/leagues net::ERR_FAILED
    • 请尝试使用localhost 而不是127.0.0.1
    • 哦哇......这工作!好的!感谢网络须藤。我想我现在会尝试在 heroku 上托管和运行 django,看看我是否仍然可以从 Nuxt 访问。
    • 嗨,网络须藤。在尝试使用 Django-rest 框架教程学习时,我遇到了更多问题,可在此处找到 django-rest-framework.org/tutorial/…。你觉得你能帮我吗?联系您的最佳方式是什么?
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2021-09-15
    • 2015-02-14
    • 1970-01-01
    • 2021-04-11
    • 2021-01-14
    • 2018-12-25
    • 2019-11-17
    相关资源
    最近更新 更多