【发布时间】:2021-09-04 10:22:11
【问题描述】:
我正在使用 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 });
});
我的问题是当我尝试从 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 } };
},
});
我收到以下回复: 错误:“not_authenticated”,描述:“用户没有活动会话或未通过身份验证”
有什么想法吗?谢谢!!
【问题讨论】:
-
您应该直接在
getServerSideProps中使用您的API 路由中的逻辑,而不是从您的内部API 中获取。有关详细信息,请参阅Internal API fetch with getServerSideProps? (Next.js)。 -
我明白了。我会查一下!非常感谢!