【问题标题】:Next.js and AWS Amplify getting Error: No Current User - getServerSidePropsNext.js 和 AWS Amplify 出现错误:没有当前用户 - getServerSideProps
【发布时间】:2021-11-20 19:26:13
【问题描述】:

getServerSideProps 显示“No Current User”,但我已登录我的应用。

type Post
  @model
  @key(
    name: "postsByUsername"
    fields: ["username"]
    queryField: "postsByUsername"
  )
  @auth(
    rules: [
      { allow: owner, ownerField: "username" }
      { allow: private, operations: [read] }
      { allow: public, operations: [read] }
    ]
  ) {
  id: ID!
  username: String
  image: S3Object
}

我可以使用 AWS AppSync 的网站按用户名实际查询帖子,它返回值。我使用与我的应用相同的登录名登录。

export async function getServerSideProps() {
  const SSR = withSSRContext();
  const { data } = await SSR.API.graphql({
    query: postsByUsername,
    variables: {
      username: "username" // checked in dynamodb, same username as signed in. 
    },
    authMode: "AMAZON_COGNITO_USER_POOLS",
  });
  return {
    props: {
      posts: data.postsByUsername.items,
    },
  };
}

我还在 _app.js 中添加了 ssr:

import { Amplify } from "aws-amplify";
import awsExports from "../../aws-exports";

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

aws-exports.js 中:

const awsmobile = {
    "aws_project_region": "xxxxx",
    "aws_appsync_graphqlEndpoint": "https://...",
    "aws_appsync_region": "xxxxx",
    "aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
    "aws_appsync_apiKey": "xxx-xxxxxxxx...",
    "aws_cognito_identity_pool_id": "xxxxxx",
    "aws_cognito_region": "xxxxx",
    "aws_user_pools_id": "xxxxx",
    "aws_user_pools_web_client_id": "xxxxxx",
    "oauth": {},
    "aws_user_files_s3_bucket": "xxxxxx",
    "aws_user_files_s3_bucket_region": "xxxxxx"
};

awsmobile 中的所有内容都是自动生成的。

【问题讨论】:

    标签: graphql next.js server-side-rendering aws-amplify aws-appsync


    【解决方案1】:

    您需要在 withSSRContext 函数中传递请求上下文,因此您的 getServerSideProps 函数应如下所示

    export async function getServerSideProps({ req }) {
      const SSR = withSSRContext({ req });
      ...
    }
    

    参考: https://docs.amplify.aws/lib/ssr/q/platform/js/#withssrcontext

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2022-10-12
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 2021-03-09
      • 1970-01-01
      • 2019-05-06
      相关资源
      最近更新 更多