【问题标题】:Fetching data in next.js returning undefined在 next.js 中获取数据返回未定义
【发布时间】:2021-12-01 11:58:37
【问题描述】:

我正在尝试使用 next.js 从此 API https://rapidapi.com/apidojo/api/shazam 获取数据 但我越来越不确定,我不知道是什么问题,这是代码的 sn-p,如果有人能帮助我理解我做错了什么,我会很高兴。

export async function getServerSideProps(context) {
  const res = await fetch(
    'https://shazam.p.rapidapi.com/charts/track?locale=en-US&pageSize=20&startFrom=0',
    {
      method: 'GET',
      headers: {
        'x-rapidapi-host': 'shazam.p.rapidapi.com',
        'x-rapidapi-key': 'my_key',
      },
    },
  );

  const data = await res.json();

  if (!data) {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      data: data,
    },
  };
}

【问题讨论】:

  • 如果你const data = await res.json().then(x => console.log(x))会发生什么?
  • 将其包装在 try/catch 块中并记录错误(如果有)。您可能缺少参数或使用了错误的查询值(例如 startFrom 可能需要从 1 开始,而不是 0)。
  • 我已经部分解决了这个问题,我的组件没有在每次页面刷新时都获取数据,但我不知道如何让他每次都调用该函数
  • getServerSideProps 在每个页面请求和每个页面导航中都会被调用。

标签: javascript next.js fetch


【解决方案1】:

试试这个代码 sn-p。它会为您提供更好的视角,也会抛出一些错误(如果有的话)

fetch("https://shazam.p.rapidapi.com/charts/track?locale=en-US&pageSize=20&startFrom=0", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "shazam.p.rapidapi.com",
        "x-rapidapi-key": "*****"
    }
})
.then(response => {
    console.log(response);
})
.catch(err => {
    console.error(err);
});

【讨论】:

    猜你喜欢
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多