Creating Dynamic Routes using 'getStaticPaths' and 'getStaticProps' in NextJS

Gre*_*ley 5 mongodb reactjs next.js

I am trying to create dynamic pages that show individual book details (.i.e. title/author) on a separate page based on a query string of the "id" for each book. In a previous question I asked, answers from users were very helpful and I have a much better understanding of how to use getStaticPaths and getStaticProps correctly. However, I am not quite there in my code for how to do this.

Here is the basic setup and context.

  1. I am running NextJS 9.4 and would like to use a API endpoint instead of querying the database directly.
  2. The book data is being pulled from a MongoDB Atlas Database and uses Mongoose
  3. Documents in the MongoDB have a "_id" as a unique ID.
  4. I have tried to incorporate and learn from existing Github examples and NextJS documentation but I still get the following error.

Error: A required parameter (id) was not provided as a string in getStaticPaths for /book/[id]

Here is the code I have so far. I have tried to keep the code as clean as possible for now.

export default function Book({ book }) {
    return (
        <article>
            <h1>Book Details Page</h1>
            <p>{book.title}</p>
            <p>{book.author}</p>
        </article>
    )
}

export async function getStaticPaths() {
    
    const url = `${baseUrl}/api/books/books`

    const response = await axios.get(url);

    const books = response.data

    const paths = books.map((book) => ({
        params: { id: book.id },
    }))
    
    return { paths, fallback: false }
}

export async function getStaticProps({ params }) {
    const url = `${baseUrl}/api/books/books/${params.id}`
    const res = await axios.get(url)
    const book = await res.json()

    return { props: { book }}
}
Run Code Online (Sandbox Code Playgroud)

The API endpoint looks like this:

import Book from '../../../models/Book';
import dbConnect from '../../../utils/dbConnect';

// conects to the database
dbConnect();

// This gets all the book from the database
export default async (req, res) => {
    const books = await Book.find()
    res.status(200).json(books)
}
Run Code Online (Sandbox Code Playgroud)

Any support or feedback would be greatly appreciated. Once I get this working, I can hopefully be able to understand and help assist others in creating dynamic routes with NextJs. Thank you.

Nik*_*lev 5

您无法调用getStaticProps或内的 Next.js API 路由getStaticPaths。这些函数是在构建时执行的,因此没有服务器正在运行来处理请求。您需要直接向DB发出请求。

如果您想保持干净,您可以创建一个帮助器模块,例如allBooksIds()并将数据库查询保留在单独的文件中。

查看相同的问题 - NextJS getStaticProps 中的 API 调用