如何在 remix run 中从实用程序函数重定向

发布于 2025-01-15 04:53:58 字数 921 浏览 2 评论 0原文

我正在使用 Remix-run,我想从 auth 实用程序函数重定向到我的登录页面。但它不起作用。 类似的函数

import { redirect } from 'remix';

 async function authenticate(request){
  try{
    const user = await rpc.getUser(request);
    return user
  } catch(e){
   console.log(e) // logs error when rpc fails
   if(e.response.status === 401){
    return redirect('/login')
   }
   return redirect('/500')
  }
 }

这是与我的身份验证实用程序方法//component.jsx

import {useLoaderData } from 'remix';

export async function loader({ request }) {
  const user = await auth.authenticate(request);
  return { user };
}

export default function Admin(){
 const { user } = useLoaderData();
  return <h1>{user.name}</h1>
}

,如果 auth rpc 失败,我会在日志中收到错误消息。但重定向永远不会发生。 如果我将 redirect 部分移动到我的加载器函数中,它就会按预期工作。它不仅在效用函数内部工作

I am using Remix-run and i want to redirect to my login page from a auth utility function. but it doesnt work. here is a similar function to my authentication utility method

import { redirect } from 'remix';

 async function authenticate(request){
  try{
    const user = await rpc.getUser(request);
    return user
  } catch(e){
   console.log(e) // logs error when rpc fails
   if(e.response.status === 401){
    return redirect('/login')
   }
   return redirect('/500')
  }
 }

//component.jsx

import {useLoaderData } from 'remix';

export async function loader({ request }) {
  const user = await auth.authenticate(request);
  return { user };
}

export default function Admin(){
 const { user } = useLoaderData();
  return <h1>{user.name}</h1>
}

if the auth rpc fails i get the error in the logs. but redirect never happens.
If i move redirect part to my loader function it works as expected. its not only working inside the utility function

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱娆 2025-01-22 04:53:58

在深入研究文档和重新混合笑话应用程序演示后。我发现您需要从加载器/操作之外的任何其他函数抛出重定向才能进行重定向。如果需要的话,你也可以抛出 Http 响应。

import { redirect } from 'remix';

 async function authenticate(request){
  try{
    const user = await rpc.getUser(request);
    return user
  } catch(e){
   if(e.response.status === 401){
    throw redirect('/login')
   }
   throw redirect('/500')
  }
 }

After digging in the docs and remix jokes app demo. i found that you need to throw a redirect from any other function other than loaders/actions to do redirects. you can also throw Http response if wanted.

import { redirect } from 'remix';

 async function authenticate(request){
  try{
    const user = await rpc.getUser(request);
    return user
  } catch(e){
   if(e.response.status === 401){
    throw redirect('/login')
   }
   throw redirect('/500')
  }
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文