繁体   English   中英

如何在混音运行中从实用程序 function 重定向

[英]how to redirect from a utility function in remix run

我正在使用 Remix-run,我想从身份验证实用程序 function 重定向到我的登录页面。但它不起作用。 这是与我的身份验证实用程序方法类似的 function

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部分移动到我的加载器 function,它会按预期工作。 它不仅在实用程序 function 中工作

在挖掘文档并重新混合笑话应用演示之后。 我发现您需要从除加载程序/操作以外的任何其他功能进行重定向来进行重定向。 如果需要,您也可以抛出 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')
  }
 }

遗憾的是,这对我不起作用。

我正在尝试根据状态更新以编程方式重定向。 为此,我创建了这个 fn:

const redirectToNested = (to) => {
  throw redirect('/to');
};

它位于我的反应组件、加载程序或操作之外。 我仍然遇到错误“错误:无法初始化'routeModules'。这通常发生在您的客户端模块中有服务器代码时。”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM