在设置标记之前Redux Saga 调用API

sr4lhrrt  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(152)

我尝试使用keycloak实现一个带有身份验证的react应用程序,听起来不错,但当我刷新页面并获取api时, Saga 会在设置令牌之前执行调用
这是我的 Saga 故事

function* getAPI(action) {
    const state = yield select();
    try {
        let response = yield call(
            axiosRequest,
            "get",
            BaseURL,
            `/foo/mini`,
            {},
            setAuthorizationBearer(state.auth.token),
            { sendToken: true },
            "application/json"
        );
        yield put({ type: `${action.type}_SUCCESS`, payload: response, metadata: action.metadata })
    } catch (e) {
        yield put({ type: `${action.type}_ERROR`, payload: e })
    }
}

这是我的axios请求示例

import axios from "axios";
let authorizationBearer = null;

export const setAuthorizationBearer = token => {
  authorizationBearer = token;
};

const instance = (
  method,
  baseURL = process.env.REACT_APP_ENDPOINT,
  url,
  data = null,
  headers = null,
  sendToken = true,
  contentType
) => {
  return new Promise((resolve, reject) => {
    const p = {
      sendToken: sendToken.sendToken,
      data: {
        ...data,
      },
    };

    const req = axios.create({
      method,
      baseURL,
      url,
      timeout: 30000,
      headers: headers,
      crossDomain: true,
    });
    headers = {};
    if (p.sendToken && authorizationBearer) {
      headers.Authorization = `Bearer ${authorizationBearer}`;
      headers["Content-Type"] = contentType;
    }
    req({
      method,
      baseURL,
      url,
      data,
      headers,
      sendToken,
    })
      .then((payload) => {
        if (payload) {
          if (payload.status < 400) {
            resolve(payload);
          } else {
            reject(payload);
          }
        } else {
          reject(payload);
        }
      })
      .catch((e) => {
        if (axios.isCancel(e)) {
          console.log("Request canceled", e.message);
        } else {
          // handle error
        }
        reject(e);
      });
  });
};

export default instance;

最后,我用一个调度程序将我的令牌设置为身份验证。

const dispatch = useDispatch()

<ReactKeycloakProvider onTokens={({token}) => dispatch(authUser(token))} authClient={Keycloak(config)}
        initOptions={{
          onLoad: 'login-required',
          checkLoginIframe: false,
          timeSkew: "0",
          refreshToken: ""
        }}
        LoadingComponent={<div />}
      >
....
</ReactKeycloakProvider>
stszievb

stszievb1#

很可能是在执行onTokens之前呈现了应用程序内容。在呈现任何内容(或显示加载屏幕)之前,请尝试检查存储状态中是否存在令牌。

相关问题