如何从服务器组件查询NextJS路由处理程序并从Supabase获取数据

von4xj4u  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(208)

每当我试图从NextJS中的服务器组件中的路由处理程序中获取数据时,查询是由服务器进行的,因此路由处理程序返回以下错误:{ error: 'JSON object requested, multiple (or no) rows returned' }
当我尝试“手动”查询我的路由处理程序时,我没有问题,因为我设置了supabase-auth-token。所以routeHandler中的createRouteHandlerSupabaseClient没有问题。
但是当服务器这样做时,我认为它不能被认证为“我”。具体来说,我已经从supabase文档here中正确地设置了先决条件。我正在使用NextJS 13和'app'目录。
/app/API/customroute/[id]/page.jsx

const res = await fetch(`${process.env.HOST}/api/customroute/` + params.id)
    const test = await res.json()
    console.log(test)

/app/customotherroute/[id]/route.js

export async function GET(req, { params }) {
    const supabase = createRouteHandlerSupabaseClient({
        headers,
        cookies
    });
    const { data, error } = await supabase
        .from('table')
        .select('*,other_table(column)')
        .eq('id', params.id)
    if (error == null) {
        return NextResponse.json({ data });
    }
    return NextResponse.json({ error: error.message });
}

我可以回去直接在我的服务器组件中使用createServerComponentSupabaseClient来收集数据,但为了代码复制,我更喜欢使用API。我是不是漏掉了什么?
我尝试使用const { data: { user } } = await supabase.auth.getUser()在路由处理程序中设置用户数据,但它不起作用。

hivapdat

hivapdat1#

好吧,经过大量的挖掘,我找到了(明显的)答案。这是NextJS中的一个bug。当调用routehandler时,服务器没有正确地传递cookie。所以cookies列表是空的。这是记录在这个youtube视频从supabase。https://youtu.be/KmJN-bEayeY?t=600当前的解决方法是在服务器组件内部实现查询。

相关问题