Reactjs 如何为APISOUT创建拦截器?

Reactjs 如何为APISOUT创建拦截器?,reactjs,react-router,Reactjs,React Router,我使用APISOUP进行React应用程序的HTTP工作,还使用React路由器和Redux Saga 我有一个问题,我们是否有办法在Apisoup中创建拦截器,是否有可能将我们的应用程序重定向到/login路由 我添加了监视器,这是Apisoup的一个功能,但我不知道如何将我的应用重定向到那里/登录路径 谢谢你的帮助 我的显示器示例: constructor() { this.api = apisauce.create({ baseURL: env.API_URL, hea

我使用APISOUP进行React应用程序的HTTP工作,还使用React路由器和Redux Saga

我有一个问题,我们是否有办法在Apisoup中创建拦截器,是否有可能将我们的应用程序重定向到/login路由

我添加了监视器,这是Apisoup的一个功能,但我不知道如何将我的应用重定向到那里/登录路径

谢谢你的帮助

我的显示器示例:

constructor() {
  this.api = apisauce.create({
    baseURL: env.API_URL,
    headers: {
      Authorization: `Bearer ${localStorage.getItem('user') || ''}`,
    },
    timeout: 15000,
  });

  this.api.addMonitor(this.tokenMonitor);
}

private tokenMonitor(response: any) {
  const { ok, status } = response;

  if (!ok && status !== 200) {
    // I should do redirect here
    localStorage.removeItem('user');
  }
}

也许你可以用,像这样的:

constructor() {
  this.api = apisauce.create({
    baseURL: env.API_URL,
    headers: {
      Authorization: `Bearer ${localStorage.getItem('user') || ''}`,
    },
    timeout: 15000,
  });

  api.axiosInstance.interceptors.request.use(
    (config) => {
      const token = JSON.parse(localStorage?.getItem('token')) || {};
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      // config.headers['Content-Type'] = 'application/json';
      return config;
    },
    (error) => {
      Promise.reject(error);
    },
  );

  this.api.addMonitor(this.tokenMonitor);
}

private tokenMonitor(response: any) {
  const { ok, status } = response;

  if (!ok && status !== 200) {
    // I should do redirect here
    localStorage.removeItem('user');
  }
}

我希望这会有所帮助。

这很好,我相信如果我们只为需要令牌的请求传递令牌会更好。现在,在我看来,我们将其添加到所有请求中,然后根据响应将其删除?