Javascript fetch() 没有从本地主机返回预期的 json

我有一个提供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 请求。


墨色风雨
浏览 133回答 3
3回答

慕运维8079593

您需要将响应更新为 json,如下所示:const&nbsp;API&nbsp;=&nbsp;'127.0.0.1:8000/posts/'; fetch(API) &nbsp;&nbsp;&nbsp;&nbsp;.then(response&nbsp;=>&nbsp;response.json()) &nbsp;&nbsp;&nbsp;&nbsp;.then(response&nbsp;=>&nbsp;console.log(response));

慕村9548890

我认为你应该使用JSON.parse(response);或fetch(myRequest) &nbsp;&nbsp;.then(response&nbsp;=>&nbsp;response.json()) &nbsp;&nbsp;.then(data&nbsp;=>&nbsp;{console.log(&nbsp;data&nbsp;})

交互式爱情

如果后端有任何错误日志,您可以先进行,因为如果您在不同的端口上运行前端和后端,因此,首先检查是否有任何错误。您可能会遇到 CORS 错误。然后,您可以尝试使用const&nbsp;API&nbsp;=&nbsp;'127.0.0.1:8000/posts/'; fetch(API) &nbsp;&nbsp;&nbsp;&nbsp;.then(response&nbsp;=>&nbsp;response.json()) &nbsp;&nbsp;&nbsp;&nbsp;.then(response&nbsp;=>&nbsp;console.log(response));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript