【问题标题】:React Axios Interceptors jumping in lateReact Axios 拦截器迟到
【发布时间】:2021-12-04 19:08:20
【问题描述】:

我正在处理一个小型反应项目,并使用 axios 拦截器来捕获我是在本地开发环境中还是在生产部署的网站上。 发生的情况是,当人们注册我的网站时,他们点击确认电子邮件链接,然后进入某个“状态”或任何您称之为的应用程序,或者 axios 拦截器不知道我所在环境的应用程序,并且在一瞬间,在它调用正确的 api uri 之后,在右侧进行了错误的 api 调用。

让我用一些代码来展示一下:

    export const App = () => {
      useEffect(() => {
        axios.interceptors.request.use((req) => {return { ...req, url: getBaseUri() + req.url 
      };})}, []);

return (
  <div className="App">
   <Routes />
  </div> 
 )}

然后是方法:

const devUriBase = "http://localhost:8080";
const prodUriBase = "https://my-website.herokuapp.com";export function getBaseUri() {
  return window.location.host.includes("localhost") ? devUriBase : prodUriBase;
}

然后在验证页面组件上,我自己调用 api 时,api 调用是对不正确的 url 进行的,所以在瞬间显示组件,然后似乎 useEffect 跳进去并且 api再次拨打电话。我试过的组合都没有奏效。我试图制作一个配置组件,并通过孩子们拥有 axios 拦截器,将它放在索引中,我不知道还有什么。我已经为此苦苦挣扎了 3 天,我想是时候问了。

import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import { useToken } from '../../auth/useToken';
import { EmailVerificationSuccess } from './EmailVerificationSuccess';
import { EmailVerificationFail } from './EmailVerificationFail';

export const EmailVerificationLandingPage = () => {
 const { verificationString } = useParams();
 const [, setToken] = useToken();
 const [state, setState] = useState('loading');

 useEffect(() => {
 const loadVerification = async () => {
 try {
 const response = await axios.put('/api/verify-email', { verificationString });
 const { token } = response.data;
 setToken(token);
 setState('success');
 } catch (e) {
 setState('error');
 }
 }

 loadVerification();
 }, [setToken, verificationString]);

 if (state === 'loading') return <p>Cargando...</p>;
 if (state === 'error') return <EmailVerificationFail />
 return <EmailVerificationSuccess />

感谢您的帮助。

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    这样做了。 添加请求拦截器时,默认情况下假定它们是异步的。当主线程被阻塞时,这可能会导致 axios 请求的执行延迟(在后台为拦截器创建了一个承诺,并且您的请求被放在调用堆栈的底部)。如果您的请求拦截器是同步的,您可以在选项对象中添加一个标志,该标志将告诉 axios 同步运行代码并避免请求执行中的任何延迟。

    axios.interceptors.request.use(function (config) {
    config.headers.test = 'I am only a header!';
    return config;
    }, null, { synchronous: true });
    

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2021-12-20
      • 2022-11-09
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2023-04-06
      • 2021-05-10
      • 2020-01-19
      相关资源
      最近更新 更多