Nextjs Auth0在getServerSideProps中获取数据 [英] Nextjs Auth0 get data in getServerSideProps

查看:0
本文介绍了Nextjs Auth0在getServerSideProps中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Auth0对用户进行身份验证。

IM受保护的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_AUTHENTIAD&QOOT;,描述:&QOOT;用户没有活动会话或未经过&QOOT;身份验证

有什么想法吗,伙计们?谢谢!!

api

当您从getServerSideProps受保护的推荐答案终结点调用时,您没有将任何用户的上下文(如Cookies)传递给请求,因此,您没有通过身份验证。

当您从useEffect调用时,它在您的浏览器中运行,该浏览器将所有Cookie附加到请求,其中之一是会话Cookie。

您需要将浏览器传递给getServerSideProps的会话Cookie转发到API调用。

export const getServerSideProps = withPageAuthRequired({
  async getServerSideProps(ctx) {
    const res = await fetch('http://localhost:3000/api/secret', {
      headers: { Cookie: ctx.req.headers.cookie },
// ---------------------------^ this req is the browser request to the getServersideProps
    });
    const data = await res.json();

    return { props: { data } };
  },
});

用于more info

这篇关于Nextjs Auth0在getServerSideProps中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆