【问题标题】:No current user - getServerSideProps Next JS and AWS Amplify没有当前用户 - getServerSideProps Next JS 和 AWS Amplify
【发布时间】:2021-05-04 15:40:09
【问题描述】:

我正在尝试使用 AWS Amplify 和 Next JS 在 getServerSideProps 的服务器端发出经过用户身份验证的 GraphQL 请求。

我的 AWS 数据库中的用户只有作为文档的所有者才能访问数据。

我从中得到的错误是 "No current user"...(正在登录服务器)。 问题是,我需要 getServerSideProps 中可用的用户,这样我才能使经过身份验证的请求发生。

这是我目前拥有的代码

index.tsx:

import Amplify, { API, graphqlOperation, withSSRContext } from "aws-amplify";
import config from "../aws-exports";
Amplify.configure({ ...config, ssr: true });

function Index({ bankAccounts }: { bankAccounts: BankAccount[] }) {

  return (
    ...stuff...
  );
}

index.tsx (getServerSideProps):

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { API } = withSSRContext(context);

  const result = (await API.graphql({
    query: listBankAccounts,
  })) as {
    data: ListBankAccountsQuery;
    errors: any[];
  };

  if (!result.errors) {
    return {
      props: {
        bankAccounts: result.data.listBankAccounts.items,
      },
    };
  }

  return {
    props: {
      bankAccounts: [],
    },
  };
};

如果您能提供任何帮助或建议,我将不胜感激!

【问题讨论】:

  • 我也遇到了这个问题。你能解决问题吗?提供authMode 的解决方案对我不起作用

标签: reactjs amazon-web-services graphql next.js aws-amplify


【解决方案1】:

看起来您可能只需要在您的 API.graphql 调用中也传递 authMode

SSR Support for AWS Amplify 博客文章中,在标题为在getServerSideProps 中发出经过身份验证的API 请求 的部分中,您将看到如下所示的代码示例(注意下面添加的authMode ,我在上面的代码示例中没有看到):

  const { API } = withSSRContext(context)
  let movieData
  try {
    movieData = await API.graphql({
      query: listMovies,
      authMode: "AMAZON_COGNITO_USER_POOLS"
    });
    console.log('movieData: ', movieData)
  } catch (err) {
    console.log("error fetching movies: ", err)
  }
  return {
    props: {
      movies: movieData ? movieData.data.listMovies.items : null
    }
  }
}```

【讨论】:

    猜你喜欢
    • 2022-10-12
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 2019-05-06
    • 2020-09-29
    • 2020-09-20
    相关资源
    最近更新 更多