【发布时间】:2022-10-12 23:05:32
【问题描述】:
尝试从 getServerSideProps 进行 API 调用时,我收到“没有当前用户”错误。这是一个 AWS Amplify+ NextJs 项目。 API 是受 AWS Cognito 身份验证保护的 REST API。
export async function getServerSideProps({req}) {
const { Auth, API } = withSSRContext({req});
try {
const apiName = "productApi-dev";
const path = `/products`;
products = await API.get(apiName, path); // this works perfectly in useEffect hooks
} catch (e) {
console.log(e);
}
return {
props: {
products,
},
};
}
API 调用可以在代码的其他部分完美运行,例如,在 useEffect 挂钩中。
我从 serverSideProps 测试了以下代码
const user = await Auth.currentAuthenticatedUser();
console.log(user)
它打印所需的输出用户信息。没有错误。
这是aws放大配置
Amplify.configure({
Auth: {
mandatorySignIn: true,
region: "us-east-1",
userPoolId: *****,
userPoolWebClientId: *****,
identityPoolId: i*****,
signupAttributes: "EMAIL",
secure: true,
},
API: {
endpoints: [
{
name: "*******",
endpoint: "https://*******.execute-api.us-east-1.amazonaws.com",
region: "us-east-1",
custom_header: async () => {
return {
Authorization: `Bearer ${(await Auth.currentSession())
.getIdToken()
.getJwtToken()}`,
};
},
},
],
},
ssr: true,
});
在这篇文章AWS Amplify Doc 中,在“在 getServerSideProps 中发出经过身份验证的 API 请求”部分下,它说“使用新的 withSSRContext 实用程序,您可以从这些服务器渲染的路由对 GraphQL 和 REST 后端进行经过身份验证的 API 调用。”。该示例使用 GraphQL,在发出请求时,它提到了 authMode:
movieData = await API.graphql({
query: listMovies,
authMode: "AMAZON_COGNITO_USER_POOLS"
});
我还没有找到任何关于 Rest API 的东西。
我将非常感谢任何帮助。
【问题讨论】:
-
你想清楚了吗?我面临同样的问题。
标签: amazon-web-services next.js amazon-cognito aws-amplify aws-serverless