ReactJS 无法从本地主机获取和显示数据 API

ReactJS can't fetch and display data from localhost API

下面是我用 Golang http://localhost:8081/post,

编写的用于从本地主机 api 获取数据的代码
const HomePost1 = () => {
    const [author, setName] = useState('');

    const [title, setTitle] = useState('');


    useEffect(() => {
        (
            async () => {
                const response = await fetch('http://localhost:8081/post', {
                    headers: {'Content-Type': 'application/json'},
                    credentials: 'include',
                });

                const content = await response.json();

                setName(content.author)
                setTitle(content.title)
            }
        )();
    });

    return (
        <div>
            {"welcome " + author}
            {"content:" + title}
        </div>
    )
}

我在网页上显示了这个,没有错误信息:

welcome undefined content:undefined

来自本地主机的 api 如下所示:

{
messges: [
{
   id: 2,
   title: "This is second sample post",
   author: "DEF"
},
{
   id: 3,
   title: "This is third sample post",
   author: "DEF"
}
]
}

当我从另一个 api 获取数据时,我使用了完全相同的方法,我编写并成功显示了结果。这可能是什么问题?这是前端还是后端造成的?

根据api结果,响应包含一个数组。

您可以尝试在控制台中打印出变量“content”,以查看对象结构。

我建议你可以这样尝试:

content[0].title
// OR
content.messges[0].title

您的 api 已发送数组,因此您应该使用 map() 而不是直接调用 content.title 这是工作示例。

const HomePost1 = () => {
const [res, setRes] = useState([]);

useEffect(() => {
    (
        async () => {
            const response = await fetch('http://localhost:8081/post', {
                headers: {'Content-Type': 'application/json'},
                credentials: 'include',
            });

            const content = await response.json();

            setRes(content.messges)
        }
    )();
});

return (

    <div>
       { res.map((rec, i ) => {
          return (<div key={i}>{"welcome " + rec.author}
          {"content:" + rec.title}</div>)
        }) }
    </div>
)
}