django-cors-headers CORS_ORIGIN_WHITELIST 元组与字符串问题

Posted

技术标签:

【中文标题】django-cors-headers CORS_ORIGIN_WHITELIST 元组与字符串问题【英文标题】:django-cors-headers CORS_ORIGIN_WHITELIST tuple vs string issue 【发布时间】:2018-11-25 14:17:12 【问题描述】:

我正在尝试将 django-cors-headers 用于我的项目。

当我将 CORS_ORIGIN_WHITELIST 设置为字符串时它会出现,它工作正常。但是当我将它用作元组时,它不起作用。知道为什么吗?我在文档中找不到任何关于使用元组或字符串之间区别的具体内容。

要加载 JSON,我使用的是 jQuery $.getJSON()

$.getJSON( "http://127.0.0.1:8000/accounts/api_r/44234138/?format=json", function( data ) 
  var items = [];
  $.each( data, function( key, val ) 
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  );

  $( "<ul/>", 
    "class": "my-new-list",
    html: items.join( "" )
  ).appendTo( "#foo" );
);

【问题讨论】:

您是否在设置中包含了 CORS 中间件,如下所示:'corsheaders.middleware.CorsMiddleware' 【参考方案1】:

我遇到了同样的问题。我相信这个问题与字符串编码有关。如果您将白名单更改为以下内容,它应该适合您:

CORS_ORIGIN_WHITELIST = (
    u'http://localhost:8888',
    u'http://127.0.0.1:8000',
)

很遗憾,我没有给你一个“为什么”,但至少这应该能让你继续前进。

【讨论】:

基本规则是你应该覆盖所有的基本网址。就像我使用 react 一样,因为 react 应用程序位于端口 3000,所以我必须将其包含在白名单中。我的白名单是这样的 - CORS_ORIGIN_WHITELIST = [ 'localhost:3000', 'localhost:8000', 'localhost:8080', ] 并且不要忘记像这样添加 cors 中间件:'corsheaders.middleware.CorsMiddleware'

以上是关于django-cors-headers CORS_ORIGIN_WHITELIST 元组与字符串问题的主要内容,如果未能解决你的问题,请参考以下文章

django-cors-headers

Django-cors-headers 不工作

使用 Postman 时 django-cors-header 无法按预期工作

即使使用 django-cors-headers 也得到 304 响应

Wagtail、CORS 和 Django-Cors-Headers。如何启用 CORS 以便 AXIOS 可以访问端点

django-cors-header 出现问题 - ModuleNotFoundError: No module named 'corsheaders'