简体   繁体   English

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

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

I am using Remix-run and i want to redirect to my login page from a auth utility function. but it doesnt work.我正在使用 Remix-run,我想从身份验证实用程序 function 重定向到我的登录页面。但它不起作用。 here is a similar function to my authentication utility method这是与我的身份验证实用程序方法类似的 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>
}

if the auth rpc fails i get the error in the logs.如果 auth rpc 失败,我会在日志中收到错误消息。 but redirect never happens.但重定向永远不会发生。 If i move redirect part to my loader function it works as expected.如果我将redirect部分移动到我的加载器 function,它会按预期工作。 its not only working inside the utility function它不仅在实用程序 function 中工作

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.如果需要,您也可以抛出 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')
  }
 }

This sadly didn't work for me.遗憾的是,这对我不起作用。

I am trying to redirect programmatically depending on a state update.我正在尝试根据状态更新以编程方式重定向。 For this purpose I created this fn:为此,我创建了这个 fn:

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

which lives outside my react component, the loader or action.它位于我的反应组件、加载程序或操作之外。 I am still getting a crash with error "Error: Cannot initialize 'routeModules'. This normally occurs when you have server code in your client modules."我仍然遇到错误“错误:无法初始化'routeModules'。这通常发生在您的客户端模块中有服务器代码时。”

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

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