我有一个提供 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
错误
更新:
我还注意到,当我刷新 javascript 页面时,Django 服务器日志中没有出现新请求。然而,当我运行curl时,有一个GET请求。
您需要将响应更新为 json,如下所示:
const API = '127.0.0.1:8000/posts/';
fetch(API)
.then(response => response.json())
.then(response => console.log(response));
我认为你应该使用
JSON.parse(response)
;
或
fetch(myRequest)
.then(response => response.json())
.then(data => {console.log( data })
您可以先检查后端是否有任何错误日志,因为如果您在不同端口上运行前端和后端,那么首先检查是否有任何错误。您可能会遇到 CORS 错误。
然后你可以尝试使用
获取数据const API = '127.0.0.1:8000/posts/';
fetch(API)
.then(response => response.json())
.then(response => console.log(response));