網站搜尋

javascript - 在 Next.js 的 Amplify 中獲取「沒有當前用戶」錯誤


我嘗試按照這個教程在 Amplify 中使用 Next.js 實現一個 SSG 應用,pages/index.tsx 運行良好。但 pages/posts/[id].tsx 無法運行,並顯示了以下錯誤。

Server Error
Error: No current user

This error happened while generating the page. Any console logs will be displayed in the terminal window.

而且控制台顯示了這個錯誤。

GET http://localhost:3000/posts/da53d1f3-775f-49c4-a311-d311f2e5623f 500 (Internal Server Error)

我在 pages/posts/[id].tsx 的程式碼如下。請問我可以請教你如何解決這個錯誤嗎?

import { Amplify, API, withSSRContext } from "aws-amplify";
import Head from "next/head";
import { useRouter } from "next/router";
import awsExports from "../../aws-exports";
import { getPost, listPosts } from "../../graphql/queries";

Amplify.configure({ ...awsExports, ssr: true });

export async function getStaticPaths() {
  const SSR = withSSRContext();
  const { data } = await SSR.API.graphql({ query: listPosts });
  const paths = data.listPosts.items.map((post: any) => ({
    params: { id: post.id },
  }));

  return {
    fallback: true,
    paths,
  };
}

export async function getStaticProps({ params }: { params: any }) {
  const SSR = withSSRContext();
  const { data } = await SSR.API.graphql({
    query: getPost,
    variables: {
      id: params.id,
    },
  });

  return {
    props: {
      post: data.getPost,
    },
  };
}

export default function Post({ post }: { post: any }) {
  const router = useRouter();

  if (router.isFallback) {
    return (
      <div>
        <h1>Loading&hellip;</h1>
      </div>
    );
  }

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}