【问题标题】:CORS Issues after adding headers field to axios when making a GET request发出 GET 请求时将标头字段添加到 axios 后的 CORS 问题
【发布时间】:2021-10-21 09:43:44
【问题描述】:

我将 Django REST 用于我的 API/后端。

这是我的python代码:

   INSTALLED_APPS = [
            ...
       "rest_framework",
       "corsheaders",
            ...
    ]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]





CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]

CORS_ORIGIN_WHITELIST = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]

在我的 React JS 前端:

listItems = async () =>{
    let fetchedItems = await axios.get("http://localhost:8000/api/shipments/list/", {headers: {accessToken: this.props.token, "Access-Control-Allow-Headers" : '*'}});
}

当我有没有标题部分的 listItems 时,我没有收到任何 CORS 错误:

listItems = async () =>{
    let fetchedItems = await axios.get("http://localhost:8000/api/items/list/"});
}

但是,我需要在请求的标头中传递 accessToken。

这是我得到的错误:

CORS 策略已阻止从源“http://localhost:8000/api/items/list/”访问位于“http://localhost:8000/api/items/list/”的 XMLHttpRequest:Access 不允许请求标头字段 accesstoken -Control-Allow-Headers 在预检响应中。

出现此类 CORS 问题的原因是什么,解决它的最佳方法是什么?

【问题讨论】:

  • 尝试在您的CORS_ALLOW_HEADERS 设置中添加accesstoken

标签: javascript reactjs django django-rest-framework axios


【解决方案1】:

所以问题可能出在您评论的中间件上 在您发送的示例中,没有INSTALLED_APPS的迹象

INSTALLED_APPS 应该是这样的


INSTALLED_APPS = [
     ...
    "rest_framework",
    "corsheaders",
     ...
]

【讨论】:

    【解决方案2】:

    如果您的唯一目的是测试(而非生产),您可以在 settings.py 文件中添加 CORS_ORIGIN_ALLOW_ALL = True

    【讨论】:

      【解决方案3】:

      对于未来的读者,用 Django / Django REST 解决 CORS 问题。

      在您的 settings.py 文件中,添加:

      CORS_ALLOW_HEADERS = [
          "name of the thing you are passing in the header",
          "Access-Control-Allow-Headers",
          "name of the thing you are passing in the header (all lower cased)",
      ]
      

      就我而言,解决问题的方法如下:

      CORS_ALLOW_HEADERS = [
          "accessToken",
          "Access-Control-Allow-Headers",
          "accesstoken",
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-03
        • 2018-07-01
        • 2016-03-24
        • 1970-01-01
        • 2014-07-06
        • 1970-01-01
        • 2016-09-28
        • 2014-09-23
        相关资源
        最近更新 更多