【发布时间】: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 => response.json()).then(response => console.log(response))而不是相反 -
我都试过了。没有任何效果!
-
尝试在您的 IP 前添加
http:// -
请同时发布
response.headers和.then(response => response.text())结果以帮助调试。 -
检查浏览器开发控制台。如果由于 CORS 或任何其他问题导致提取失败,它将创建一个错误行。
标签: javascript json fetch fetch-api