【问题标题】:Access to XMLHttpRequest at 'http://localhost:8000/api/posts/' from origin 'http://localhost:3000' has been blocked by CORS policy. Django and ReactCORS 策略已阻止从源“http://localhost:3000”访问“http://localhost:8000/api/posts/”处的 XMLHttpRequest。 Django 和反应
【发布时间】:2020-12-18 09:24:17
【问题描述】:

我正在使用 Django 和 React 创建一个全栈应用程序。

我创建了一个使用 cookie 的组件查找。这是我的代码:

  function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
          var cookie = cookies[i].trim();
          if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
          }
      }
  }
  return cookieValue;
}

function lookup(method, endpoint, callback, data) {
  let jsonData;
  if (data){
    jsonData = JSON.stringify(data)
  }
  const xhr = new XMLHttpRequest()
  const url = `http://localhost:8000/api${endpoint}`
  xhr.responseType = "json"
  const csrftoken = getCookie('csrftoken');
  xhr.open(method, url)
  xhr.setRequestHeader("Content-Type", "application/json")

  if (csrftoken){
    xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
    xhr.setRequestHeader("X-CSRFToken", csrftoken)
  }
  
  xhr.onload = function() {
    callback(xhr.response, xhr.status)
  }
  xhr.onerror = function (e) {
    console.log(e)
    callback({"message": "The request was an error"}, 400)
  }
  xhr.send(jsonData)
}

export function createPost(newPost, callback){
  lookup("POST", "/posts/create/", callback, {content: newPost})
}

export function loadPosts(callback) {
    lookup("GET", "/posts/", callback)
}

此代码导致我的前端出现此错误:(后端工作正常) 从源“http://localhost:3000”访问“http://localhost:8000/api/posts/”处的 XMLHttpRequest 已被 CORS 策略阻止:Access-Control-Allow- 不允许请求标头字段 http_x_requested_with预检响应中的标头。

现在,我意识到如果我删除这个:

 if (csrftoken){
    xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
    xhr.setRequestHeader("X-CSRFToken", csrftoken)
  }

我的代码运行良好。

  1. 为什么会这样?如果还有什么需要上传的,请告诉我
  2. 如果只是我的个人项目,您认为跳过 csrftoken 是否合理?

【问题讨论】:

    标签: django reactjs csrf csrf-token


    【解决方案1】:

    首先,您的 django 环境中是否安装了 corsheaders? 如果不安装pip install django-cors-headers

    然后在你的 settings.py 中添加:

    INSTALLED_APPS = [
    ...
    'corsheaders',
    ...]
    
    MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...]
    
    CORS_ALLOWED_ORIGINS = [
    "https://example.com", //ADD YOUR REACT IP IN THIS LIST
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000"]
    

    然后尝试再次调用您的后端,它现在应该可以工作了。

    【讨论】:

    • 感谢您的回答。它已安装,我的代码中都有。很抱歉没有在上面提到这一点。
    • 好的,也许为了更好地关注问题尝试使用这个扩展:chrome.google.com/webstore/detail/allow-cors-access-control/… 如果它有效,问题出在 csrf 中
    • 好的,所以我测试了 CORS 并且 CORS 不允许用于任何请求方法。我将浏览器添加到白名单中,并且不再出现错误。但是,我认为我的后端在处理提交的数据时存在问题。
    • 是的。我认为我的问题可能在于我在前端处理 POST 的方式。无论如何,感谢您的帮助:)
    【解决方案2】:

    我遇到了完全相同的问题。但我所做的只是在我的 settings.py 中添加 CORS_ALLOW_HEADERS ,仅此而已:

    **
    CORS_ALLOW_HEADERS = ['*'] //This line did the magic for me
    **  
    

    还有以下内容:

    INSTALLED_APPS = [
         ...
        'corsheaders',
         ...
    ]
    
    MIDDLEWARE = [
         ...
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        ...
    ]
    
    ALLOWED_HOSTS = ['*']
    
    CORS_ALLOW_ALL_ORIGINS = True
    

    下面这行与包含 api like 的 url 有关 http://localhost:8000/api/anytext

    CORS_URLS_REGEX = r'^/api/.*$'
    

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 2021-03-14
      • 2021-01-24
      • 2021-03-08
      • 2021-10-05
      • 1970-01-01
      • 2021-01-23
      • 2019-12-16
      • 1970-01-01
      相关资源
      最近更新 更多