【问题标题】:Javascript fetch() not returning expected json from localhostJavascript fetch() 没有从本地主机返回预期的 json
【发布时间】:2021-03-08 23:34:01
【问题描述】:

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

【问题讨论】:

  • 您是否在console.log 之前运行response.json()?如:您的代码应如下所示:fetch(API).then(response =&gt; response.json()).then(response =&gt; console.log(response)) 而不是相反
  • 我都试过了。没有任何效果!
  • 尝试在您的 IP 前添加 http://
  • 请同时发布response.headers.then(response =&gt; response.text()) 结果以帮助调试。
  • 检查浏览器开发控制台。如果由于 CORS 或任何其他问题导致提取失败,它将创建一个错误行。

标签: javascript json fetch fetch-api


【解决方案1】:

您需要将响应更新为如下所示的 json:

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

【讨论】:

    【解决方案2】:

    我认为你应该使用JSON.parse(response)

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

    【讨论】:

    【解决方案3】:

    如果后端有任何错误日志,你可以先检查,因为如果你在不同的端口上运行前端和后端,所以,首先检查是否有任何错误。你可能有 CORS 错误。

    然后你可以尝试获取数据

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

    【讨论】:

    • 我没有注意到它实际上向后端发送了请求。
    • 应该,即使您从控制台尝试过。它将发送请求,我们将能够看到后端请求。可能是第一个请求是选项请求,而您找不到它。
    • 我在 curl 请求中看到了它。可能是前端找不到后端的问题?
    • 可能是这样。在后端端点上添加日志并检查请求是否在那里竞速
    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2012-11-09
    • 2013-09-04
    • 2017-12-11
    相关资源
    最近更新 更多