首页 > 解决方案 > fetch 显示 next.js 中未定义的数据

问题描述

当我在 header.js 或 footer.js 中使用 fetch 并将它们包含到我的 layout.js 中时,我得到的值未定义。相同的代码在 index 或 about 等单独的页面上运行良好。

 static async getInitialProps(){
    const response =  fetch('http://localhost/coc/api/singletons/get/topbar/',{
      headers: { 'Cockpit-Token': 'ae6d9be66c544f76bf4e0676357253' }
    })
    const data= response.json();
    return { data: data }

标签: next.js

解决方案


你可以尝试添加一个await吗?像这样:

const response = await fetch('http://localhost/coc/api/singletons/get/topbar/',{
      headers: { 'Cockpit-Token': 'ae6d9be66c544f76bf4e0676357253' }
    })


推荐阅读