我有一個(gè)提供JSON數(shù)據(jù)的Django后端。當(dāng)我跑步時(shí),我得到:curl 127.0.0.1:8000/posts/[{"title": "This is a title","body": "Body :)","pub_date":"2020-11-25T13:36:57Z"},...]但是,當(dāng)我運(yùn)行此js代碼時(shí)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}這是意料之中的。如果我然后嘗試運(yùn)行,我會(huì)得到.then(response => response.json())Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data當(dāng)我跑步時(shí)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))只是發(fā)回Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data錯(cuò)誤更新:我還注意到在 Django 服務(wù)器日志上,當(dāng)我刷新 javascript 頁面時(shí)沒有出現(xiàn)新的請(qǐng)求。但是,當(dāng)我運(yùn)行 curl 時(shí),有一個(gè) GET 請(qǐng)求。
Javascript fetch() 沒有從本地主機(jī)返回預(yù)期的 json
墨色風(fēng)雨
2023-09-07 17:04:30