【发布时间】:2021-10-19 13:18:24
【问题描述】:
我正在开发 cs50 网络开发项目 Network。基本上是在构建一个 twitter 模仿者。
它仍在处理中,但到目前为止,我有两个获取 JSON 响应的请求。一次完美运行,但另一个非常相似的请求返回 html 而不是 JSON,从而导致错误。无法弄清楚为什么这个不起作用。代码如下:sn-ps:
这是出于某种原因为我的 profile.html 文件返回 html 的文件。注释掉的部分是实际的 fetch JSON 请求,但我暂时将其更改为在控制台中显示返回的内容。 profile.js:
function load_posts_profile() {
console.log("load_posts_profile running");
document.querySelector('#prof-posts').style.display = 'block';
fetch(`/profile_posts`)
//.then(response => response.json())
.then(response => response.text())
.then(text => console.log(text))
//.then(posts => {
// Print posts
//console.log(posts);
//posts.forEach(post => show_posts_profile(post));
//});
}
profile.html:
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<!--insert profle name below in h3-->
<h2 id="profile-name"></h2>
<br>
<h4 id="followers"></h4>
<br>
<h4 id="following"></h4>
<!--add js to load user's posts only-->
<div id="prof-posts">
</div>
{% else %}
<strong> Login To See Profile</strong>
{% endif %}
{% endblock %}
{% block script %}
<script src="{% static 'network/profile.js' %}"></script>
{% endblock %}
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("all_posts", views.all_posts, name="all_posts"),
path("<str:poster>", views.profile, name="profile"),
path("profile_posts", views.profile_posts, name="profile_posts")
]
views.py sn-p:
def all_posts(request):
posts = Post.objects.all()
posts = posts.order_by("-timestamp").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
def profile_posts(request, poster):
posts = Post.objects.get(poster=poster)
posts = posts.order_by("-timestamp").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
def profile(request, poster):
return render(request, "network/profile.html", {
"poster": poster,
})
这是具有类似获取请求的 js 文件,它可以完美运行。为什么这个工作(即返回 JSON)而另一个返回 html?:
function load_posts() {
console.log("load_posts running");
document.querySelector('#all-posts').style.display = 'block';
fetch(`/all_posts`)
.then(response => response.json())
.then(posts => {
// Print posts
console.log(posts);
posts.forEach(post => show_posts(post));
});
}
【问题讨论】: