【问题标题】:(Jquery, Ajax, Django, Cors, GET) No 'Access-Control-Allow-Origin' header - Cors Whitelist Ignored(Jquery、Ajax、Django、Cors、GET)没有“Access-Control-Allow-Origin”标头 - 忽略 Cors 白名单
【发布时间】:2019-01-28 18:45:16
【问题描述】:

我知道这个问题经常出现,但我还没有找到一个安全的解决方案。(注意我已经匿名了下面的网址。)

问题:

  • 我已经设置了一个运行 Django 的 Apache 服务器作为 serverA 上的一个 RESTful API
  • 在 serverB 上我有一个简单的 jquery AJAX GET 请求
  • 发送请求时,我收到“No 'Access-Control-Allow-Origin' header”错误,但来源在 cors 白名单中

注意事项:

  • 我已经按照https://pypi.org/project/django-cors-headers/ 在 Django 中安装了 Cors Headers
  • 我已将 serverB 的 url 添加到 CORS_ORIGIN_WHITELIST 中
  • 如果我设置 CORS_ORIGIN_ALLOW_ALL = True 它工作正常(但不安全)
  • 直接打开 url 会给我正确的 json 响应

代码:

ServerB 上的 Jquery:

getValueWithKey : function(table, key, callback){
    uri = "serverA.com/{0}/{1}".format(table, key)
    $.ajax({
      url: uri,
      type:"GET"
      crossDomain: true,    
      dataType: 'json'
   }).done(function(data) {
       console.log(data);
       callback(data);
   });
},

标题(根据 chrome 控制台):

General:
Request URL: http://serverA.com/tablename/keyname
Request Method: GET
Status Code: 200 OK
Remote Address: serverA.com
Referrer Policy: no-referrer-when-downgrade

Response Headers:
Content-Type: application/json

Request Headers:
!Provisional headers are shown
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://serverB.com
Referer: http://serverB.com/test.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

感谢您的帮助!

【问题讨论】:

  • 您的响应标头缺少字段Access-Control-Allow-Origin : *,因此您可能没有在服务器端正确设置您的cors。
  • 谢谢,我不确定是客户端还是服务器端。仅供参考我的解决方案如下。

标签: jquery ajax django get cors


【解决方案1】:

原来我需要改变:

CORS_ORIGIN_WHITELIST=('http://example.net')

CORS_ORIGIN_WHITELIST=('example.net')

【讨论】:

    【解决方案2】:
    CORS_ORIGIN_ALLOW_ALL = True
    CORS_ALLOW_CREDENTIALS = True
    
    CORS_ALLOW_METHODS = (
        'DELETE',
        'GET',
        'OPTIONS',
        'PATCH',
        'POST',
        'PUT',
    )
    
    CORS_ALLOW_HEADERS = (
        'accept',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
    )
    
    
    INSTALLED_APPS = [
    'corsheaders'
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',
    ]
    

    【讨论】:

    • 感谢 marin,但我需要更安全的设置而不需要 CORS_ORIGIN_ALLOW_ALL 。仅供参考,我发现了我在答案中显示的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 2016-05-13
    • 2018-09-19
    • 2019-06-19
    • 2017-04-15
    • 2014-01-20
    • 2021-08-12
    • 2018-03-28
    相关资源
    最近更新 更多