小编Man*_*nos的帖子

Nextjs Auth0在getServerSideProps中获取数据

我使用 Auth0 来验证用户身份。

我受保护的 api 路由如下:

// pages/api/secret.js

import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0';

export default withApiAuthRequired(function ProtectedRoute(req, res) {
  const session = getSession(req, res);
  const data = { test: 'test' };
  res.json({ data });
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我尝试从 getServerSideProps 获取数据时,我收到 401 错误代码。

如果我使用 useEffect 我可以从 api 路由获取数据。

我试图像这样获取数据:

export const getServerSideProps = withPageAuthRequired({
  async getServerSideProps(ctx) {
    const res = await fetch('http://localhost:3000/api/secret');
    const data = await res.json();

    return { props: { data } };
  },
});
Run Code Online (Sandbox Code Playgroud)

我收到以下响应:错误:“not_authenticated”,描述:“用户没有活动会话或未经过身份验证”

大家有什么想法吗?谢谢!!

authentication auth0 next.js

1
推荐指数
1
解决办法
3150
查看次数

标签 统计

auth0 ×1

authentication ×1

next.js ×1