【问题标题】:Fetching data from API with nextjs returns nothing使用 nextjs 从 API 获取数据不返回任何内容
【发布时间】:2022-07-31 00:37:34
【问题描述】:

我最近在玩 nextjs,不知道为什么我的代码不起作用。 所以这是对 REST API 的简单调用:

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

const defaultEndpoint = 'My_probably_problematic_api';

export async function getServerSideProps(){
  const res = await fetch(defaultEndpoint);
  const data = await res.json();
  return{
    props:{
      data
    }  
  }
}
export default function Home({data}) {
  const {results = []} = data;
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={styles.main}>
        <h1 className={styles.title}>
          playing
        </h1>
        <p className={styles.description}>
          AROUND
        </p>
        <div className={styles.grid}>
          {results.map(result => {
            const {id, title} = result;
            return(
              <div key={id}className={styles.card}>
                <h2>{ title}</h2>     
              </div>
            )
          })}        
        </div>
      </main>
      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  )
}

如果我运行它,则不会获取任何数据。我知道此代码有效,因为当我将其切换到“https://rickandmortyapi.com/api/character”时 - 它正确返回数据(在前面)。我可以 console.log 来自我的 API 的响应。我的 API 响应可能有问题吗,比如结构?它看起来像这样:

[
    {
        "date": "02/02/2022, 20:10:21",
        "description": "Google Paid Search ads are one of the best digital advertising methods to target people who are actively searching and in the market for the products or services that your business offers. However, if you’re not experienced with Google Ads then you may fin",
        "id": "29dc9f038b5ee4bd68e96298627d5806c72e1f927b73077d725a86239a97d94f",
        "image": "https://activebusinessgrowth.ca/wp-content/uploads/2022/02/TN-23-Improve-ads.png",
        "link": "https://activebusinessgrowth.ca/5-ways-to-drastically-improve-your-google-ads/",
        "tag": "Digital Marketing",
        "title": "5 Ways To Drastically Improve Your Google Ads"
    },
    {next item, etc}

返回正确数据的 API 响应(https://rickandmortyapi.com/api/character)如下所示:

{
    "info": {
        "count": 826,
        "pages": 42,
        "next": "https://rickandmortyapi.com/api/character?page=2",
        "prev": null
    },
    "results": [
        {
            "id": 1,
            "name": "Rick Sanchez",
            "status": "Alive",
            "species": "Human",
            "type": "",
            "gender": "Male",
            "origin": {
                "name": "Earth (C-137)",
                "url": "https://rickandmortyapi.com/api/location/1"
            },
            "location": {

当然,我正在将 {title} 更改为来自 Rick and Morty API 的其他匹配键。 仍然 - 我不知道为什么在我自己的 API 上 - 没有任何反应。如果这是微不足道的问题,请原谅我,这就像我与 nextjs 的第一天一样,我找不到解决方案。

【问题讨论】:

  • 您可以从 chrome 开发工具、网络选项卡中找到很多关于正在发生的事情。 (顺便说一句,rick and morty 表示对 api 的品味很高)
  • 如果您获取的数据遵循[{...}, {...}, ...] 格式,则意味着它没有results 属性,它只是一个对象数组。这意味着组件中的results 将始终是一个空数组。您应该直接从 data 变量映射项目,例如data.map(result =&gt; { ... }.
  • @juliomalves 非常感谢你,现在它正在工作:)

标签: api rest next.js


【解决方案1】:

正如@juliomalves 在评论中所说 - 映射错误,这里是固定的 Home 功能:

export default function Home({data}) {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={styles.main}>
        <h1 className={styles.title}>
          pill
        </h1>
        <p className={styles.description}>
          daily
        </p>
        <div className={styles.grid}>
          {data.map(result => {
            const {id, title} = result;
            return(
              <div key={id}className={styles.card}>
                <h2>{ title }</h2>  
              </div>
            )
          })}        
        </div>
      </main>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2016-04-25
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多