【发布时间】:2022-11-04 00:56:58
【问题描述】:
我的localhost:8000/ 端口上有一个 API 端点;此端点仅返回以下对象{"message": "hello"}。
我想使用我的 React JS 脚本来获取这个对象。我的脚本添加在下面。
import React, {useEffect, useState} from "react";
const App = () => {
const [message, setMessage] = useState("");
const getHomePageData = async () => {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = await fetch("/", requestOptions)
if (!response.ok) {
console.log("Error in fetching the data!");
} else {
console.log("Data fetched correctly!");
}
return await response.json();
};
const data = getHomePageData();
console.log(data);
return(
<center><h1>Hello, world!</h1></center>
);
}
export default App;
获取数据似乎工作正常,因为我在控制台中收到以下日志:Data fetched correctly! 因此我认为我的后端一切正常。但是在下一行我收到以下错误消息:Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.
如何修复我的代码以获取 .json() 数据?
【问题讨论】:
-
使
Appfn 异步并像这样调用const data = getHomePageData();const data = await getHomePageData(); -
@Joel,我仍然遇到同样的错误:(
-
而不是
return await response.json()写const text = await response.text(); console.log(text); return JSON.parse(text);。检查控制台。我敢打赌,你没有从你的端点得到你所期望的。 -
您还可以检查网络选项卡,过滤 XHR 请求并检查响应
-
fetch("/",可能会返回/、console.log(response)的 html 以确保您得到想要的响应
标签: javascript reactjs