如何将 Django Rest API 连接到 html CSS JS 前端

How to connect Django Rest API to a html CSS JS frontend

我是编程新手,有一件事让我很困惑,我的老板让我休息一下 API 我已经完成了所有注册、登录和其他部分的应用程序。但是现在我必须创建一个前端,但是互联网上的所有教程都是关于创建 Django 的其余部分 API 以做出反应或其他一些前端框架,他们在 YouTube 上是否有关于连接到 html CSS JavaScript 在前端到 Rest API。谢谢。

如果您不想要前端,只需按照官方 django 教程学习如何从 django 提供服务 html/css/js。

从那里你可以通过 django 上下文从你的 api 传递你需要的数据,或者你可以使用 fetch 或类似的东西从 javascript 中获取它。

后者看起来像这样。

# views.py
def index(request):
    return render(request, 'index.html')

def apiview(request):
    return JsonResponse({'title', 'served from api'})

index.html
<div class="title" token={{csrf_token}}></div>
<script>
function getTitle() {
    const div = document.querySelector('title')
    const csrf_token = div.getAttribute('token')
    fetch('localhost:8000/apiview', {
        method: 'get',
        headers: {'X-CSRFToken': token}
    })
    .then(data => data.json())
    .then(data => div.innerHTML = data.title)
}
</script>