首页 > 解决方案 > Django Rest Framework CORS 阻止 XMLHttpRequest

问题描述

我已经使用具有以下设置的 Django-cors-headers 设置了我的 CORS 策略:

APPEND_SLASH=False
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    'localhost:3000',
    'localhost'
)

我还将它添加到 installed_apps 和中间件。

现在我正在为前端制作一个 React 应用程序并使用 AXIOS 来处理我的 API 请求。当我发出 API 请求以登录我的应用程序时,CORS 策略允许它。但是,如果我发出需要令牌的 API 请求,我会得到:

从源“ http://localhost:3000 ”访问“localhost:8000/api/TestConnection/”处的 XMLHttpRequest已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-扩展名,https。

似乎我需要允许 XMLHttpRequest 用于支持的协议方案,但我在 pypi 文档中找不到任何关于此的内容。

编辑:这是 AXIOS 请求:

axios.post("localhost:8000/api/TestConnection/",
    {headers:
      {
          'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
      }
    },
    { 
      testString: 'Hello API'
    })
    .then(response => {
      console.log(response)
      })
    .catch(error => {
      console.log(error);
})

谢谢!

标签: javascriptdjangodjango-rest-frameworkcorsaxios

解决方案


错误说“来自原点' http://localhost:3000 '”和“检查 cors 政策”

我看到你的 CORS 政策是

CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    'localhost:3000',
    'localhost'
)

也许尝试提供完整的 http url。所以

CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    'http://localhost:3000',
    'localhost'
)

推荐阅读