首页 > 解决方案 > NextJS 根据页面获取自定义 JSON

问题描述

我知道您可以执行以下操作


export async function getStaticProps({ params }) {

    console.log(params)
    const res = await fetch(`https://example.com/api-access/news/2021_autumn_home_style_tips`)
    const data = await res.json()
  
    if (!data) {
      return {
        notFound: true,
      }
    }
  
    return {
      props: { data }, // will be passed to the page component as props
    }
  }

但是,如果取决于用户按下的新闻项目的最后一部分需要更改怎么办。

https://example.com/api-access/news/2021_autumn_home_style_tips
https://example.com/api-access/news/2020_autumn_home_style_tips
https://example.com/api-access/news/2021_car
https://example.com/api-access/news/top_songs

例如,如何制作一个允许我运行该 slug url 的 [slug].js 页面

https://myexample.com/news/top_songs 将从https://example.com/api-access/news/top_songs

我努力了

export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {


    console.log(params)
    const res = await fetch('https://example.com/api-access/news/{slug}')
    const data = await res.json()
  
    if (!data) {
      return {
        notFound: true,
      }
    }
  
    return {
      props: { data }, // will be passed to the page component as props
    }
  }

但是得到这个错误错误

标签: jsonnext.js

解决方案


推荐阅读