我有一个提供JSON数据的Django后端。当我跑步时,我得到:curl 127.0.0.1:8000/posts/[{"title": "This is a title","body": "Body :)","pub_date":"2020-11-25T13:36:57Z"},...]但是,当我运行此js代码时const API = '127.0.0.1:8000/posts/'fetch(API).then(response => console.log(response))我得到:Response { type: "basic", url: "http://localhost:3000/127.0.0.1:8000/posts/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false}这是意料之中的。如果我然后尝试运行,我会得到.then(response => response.json())Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data当我跑步时fetch(API).then(response => console.log(response.headers))fetch(API).then(response => console.log(response.text()))我得到Headers { }Promise { "pending "} <state>: "pending"分别此外fetch(API).then(response => console.log(response.text()))fetch(API).then(response => response.json()).then(data => console.log(data))只是发回Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data错误更新:我还注意到在 Django 服务器日志上,当我刷新 javascript 页面时没有出现新的请求。但是,当我运行 curl 时,有一个 GET 请求。
3 回答
慕运维8079593
TA贡献1876条经验 获得超5个赞
您需要将响应更新为 json,如下所示:
const API = '127.0.0.1:8000/posts/'; fetch(API) .then(response => response.json()) .then(response => console.log(response));
慕村9548890
TA贡献1884条经验 获得超4个赞
我认为你应该使用JSON.parse(response)
;
或
fetch(myRequest) .then(response => response.json()) .then(data => {console.log( data })
交互式爱情
TA贡献1712条经验 获得超3个赞
如果后端有任何错误日志,您可以先进行,因为如果您在不同的端口上运行前端和后端,因此,首先检查是否有任何错误。您可能会遇到 CORS 错误。
然后,您可以尝试使用
const API = '127.0.0.1:8000/posts/'; fetch(API) .then(response => response.json()) .then(response => console.log(response));
添加回答
举报
0/150
提交
取消