亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript fetch() 沒有從本地主機返回預期的 json

Javascript fetch() 沒有從本地主機返回預期的 json

墨色風雨 2023-09-07 17:04:30
我有一個提供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));


查看完整回答
反對 回復 2023-09-07
?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

我認為你應該使用JSON.parse(response);

fetch(myRequest)
  .then(response => response.json())
  .then(data => {console.log( data })


查看完整回答
反對 回復 2023-09-07
?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

如果后端有任何錯誤日志,您可以先進行,因為如果您在不同的端口上運行前端和后端,因此,首先檢查是否有任何錯誤。您可能會遇到 CORS 錯誤。

然后,您可以嘗試使用

const API = '127.0.0.1:8000/posts/';
fetch(API)
    .then(response => response.json())
    .then(response => console.log(response));


查看完整回答
反對 回復 2023-09-07
  • 3 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號