javascript - 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);
})
谢谢!
解决方案
错误说“来自原点' http://localhost:3000 '”和“检查 cors 政策”
我看到你的 CORS 政策是
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'localhost:3000',
'localhost'
)
也许尝试提供完整的 http url。所以
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'http://localhost:3000',
'localhost'
)
推荐阅读
- javascript - 无法将组件动态附加到被读取为 viewContainerRef 的 ag-grid
- api-platform.com - 如何为同一实体公开不同的 GET 路由
- c# - 绘画事件不断触发
- jquery - 媒体查询和 JQuery
- python - 在 numpy 中处理日期
- android - 在android flow + room中,如何监控一个Flow列表
- javascript - 使用 ajax 调用从 JSON 获取数据到 HTML 表
- haskell - 比较记录的字段
- java - 有什么方法可以避免在 android embed realmobject 中出现重复?
- asp.net-web-api - 谁能告诉我如何在主键类型为 uniqueidentifier 的 sql server 中编写更新存储过程?