【发布时间】: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