繁体   English   中英

使用部分前端时处理来自 rails api 的 401 未经授权错误(反应)

[英]Handling the 401 Unauthorized error from rails api when using a partial frontend (react)

我正在使用 rails 5.2 和 Ruby 2.7。 我的前端是反应,我正在尝试访问我的项目路线。 登录/注销由 rails app/semi-api 处理(它具有除项目页面之外的其他内容的视图,即 )。 我确实知道我需要一个令牌才能通过身份验证检查,但我似乎无法找到有关如何从 Rails 获取它的任何帮助。 任何文档/博客/帖子都会很棒。 我的 Rails 应用程序使用 Devise 进行身份验证,使用 Pundit 进行授权。

从 React 应用程序发送 GET 请求(使用 axios)会立即重定向 Rails 应用程序以呈现登录页面(在未授权登录的情况下应该如此)。 相关错误的片段

const API_URL = 'http://localhost:3000/projects'

function getAPIData(){
  return axios.get(API_URL).then((response) => response.data)
  
}

function App() {
  const [bugs, setBugs] = useState([]);

  useEffect(() => {
    let mounted = true;
    getAPIData().then((items) => {
      if (mounted) {
        setBugs(items);
      }
    });
    return () => (mounted= false);
  }, [])

  return (<Router>
    <Header title='Backend'/>
    <BugList bugs={bugs}/>
    <Footer/>
    </Router>
  );
}

export default App;

上面贴的是我axios获取数据的例程。 React 在端口 4000 上运行,我的 Rails 应用程序(使用带有通配符 (*) 表达式的 rack-cors 来接受所有类型的所有请求)在端口 3000 上。

 const API_URL = 'http://localhost:3000/projects' function getAPIData(){ return axios.get(API_URL).then((response) => response.data).catch((err) => { if (err?.response?.status === 401) { } }) } function App() { const [bugs, setBugs] = useState([]); useEffect(() => { let mounted = true; getAPIData().then((items) => { if (mounted) { setBugs(items); } }); return () => (mounted= false); }, []) return (<Router> <Header title='Backend'/> <BugList bugs={bugs}/> <Footer/> </Router> ); } export default App;

暂无
暂无

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

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