我有一個提供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 請求。
Javascript fetch() 沒有從本地主機返回預期的 json
墨色風雨
2023-09-07 17:04:30