我已经构建了REST API,并且跟随本教程: https://www.youtube.com/watch?v=hISSGMafzvU&t=14s
我已经完成了全部工作,直到13分钟。在html模板中添加了JS脚本。当我运行并检查控制台时,我得到:“跨域请求被阻止:同源策略禁止读取http://127.0.0.1:8000/api/task-list/处的远程资源。(原因:缺少CORS标头'Access-Control-Allow-Origin')。 “
我不知道CORS标头进入我的项目的哪一部分?
<script type="text/javascript">
buildList()
function buildList(){
var wrapper = document.getElementById('list-wrapper')
var url = 'http://127.0.0.1:8000/api/task-list/'
fetch(url)
.then((resp) => resp.json())
.then(function(data){
console.log('Data:', data)
})
}
</script>
答案 0 :(得分:0)
您必须将pip install django-cors-headers
添加到Django应用并将其配置为允许请求。
然后将其添加到已安装的应用中:
#settings.py
INSTALLED_APPS = [
...
'corsheaders',
...
]
您还需要添加一个中间件类来侦听响应:
#settings.py
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
只允许所有来源发出跨站点HTTP请求:
#/settings.py
CORS_ORIGIN_ALLOW_ALL = True
注意:如果您正在开发中,则可以允许任何来源的所有CORS。但是不要在生产中这样做。
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'https//:yourdomain',
)
希望对您有帮助!