【问题标题】:REACT: put token from store into axios header反应:将令牌从存储放入 axios 标头
【发布时间】:2021-06-14 00:56:12
【问题描述】:

我对 React 还是很陌生,并试图将 JWT 令牌添加到我的标头以进行授权的 api 调用。

// client.ts
export const client = axios.create({
    baseURL: URLS.local,
    responseType: 'json',
    timeout: 180000,
});

const state = store.getState(); // Error caused by this
export const authClient = axios.create({
    baseURL: URLS.local,
    responseType: 'json',
    timeout: 180000,
    headers: { 'Authorization': state.account.token, 'Content-Type': 'application/json' }
});

// accountSlice.ts
export const login = createAsyncThunk(
  'account/account', 
  async () => {
    const response = await authClient.get('/api/account/account');
    return response.data;
  }
);

export const login2 = createAsyncThunk(
  'account/account', 
  async (_, { getState }) => {
    console.log('login called');
    const { token } = getState().account; // Error caused by this
    const response = await client.get('/api/account/account', {headers: { 'Authorization': token, 'Content-Type': 'application/json' }} );
    return response.data;
  }
);

const accountSlice = createSlice({
  name: 'account',
  initialState,
  // non async calls
  reducers: {
    reset: () => {
      return initialState;
    },
  },
  // async calls
  extraReducers: builder => {
    builder.addCase(authenticate.fulfilled, (state, action) => {
      state.status = 'pending';
      state.token = action.payload.idToken;
    })
    builder.addCase(login.fulfilled, (state, action) => {
      state.status = 'fulfilled';
      state.isAuthenticated = true;
      state.profile = action.payload;
    })
    builder.addCase(logout.fulfilled, (state) => {
      state = initialState;
    })
  }
})

所以我有一个获取 JWT 令牌的 post 调用,然后我将其设置为 state.token。但是现在我需要使用它来添加到我的 api 调用的所有其他标头中。 我尝试了 2 种不同的方法,但都失败了。

第一种方法是尝试访问 client.ts 中的令牌并使用标头创建 axios 客户端,但是因为我有“const state = store.getState()”,所以我的减速器提供程序之一出现错误在 store.ts 中找不到。

2ns 方法试图在进行 api 调用时在 createAsyncThunk 上添加令牌,但这里的问题是参数 {getState} 没有按预期工作(https://redux-toolkit.js.org/api/createAsyncThunk)。我目前收到此错误“‘未知’类型上不存在属性‘帐户’。”

我更喜欢第一种方法,因为如果有人知道我的代码有什么问题,它会更干净。

谢谢

【问题讨论】:

    标签: reactjs redux redux-thunk redux-toolkit


    【解决方案1】:

    当您创建 authClient 时,令牌尚未设置,您可以尝试以下操作:

    export const authClient = (getState) =>
      axios.create({
        baseURL: URLS.local,
        responseType: 'json',
        timeout: 180000,
        headers: {
          Authorization: getState().account.token,
          'Content-Type': 'application/json',
        },
      });
    
    export const login = createAsyncThunk(
      'account/account',
      async (_, thunkApi) => {
        const response = await authClient(
          thunkApi.getState
        ).get('/api/account/account');
        return response.data;
      }
    );
    

    【讨论】:

      【解决方案2】:
      export const authClient = (getState) =>
        axios.create({
          baseURL: URLS.local,
          responseType: 'json',
          timeout: 180000,
          headers: {
            Authorization: getState().account.token,
            'Content-Type': 'application/json',
          },
        });
      
      export const login = createAsyncThunk(
        'account/account',
        async (_, thunkApi) => {
          const response = await authClient(
            thunkApi.getState
          ).get('/api/account/account');
          return response.data;
        }
      );
      

      【讨论】:

        猜你喜欢
        • 2020-10-25
        • 1970-01-01
        • 2021-01-15
        • 1970-01-01
        • 2022-01-14
        • 2020-12-09
        • 1970-01-01
        • 2017-05-07
        • 2020-03-25
        相关资源
        最近更新 更多