在 rtk 查询中使用条件 header 的正确方法?

The right way to use conditional header in rtk query?

我使用 rtk 查询,我想为所有请求传递 header 身份验证,但没有 header 的刷新令牌除外,这是我的代码是否有条件或传递 [=14] =] 为空?或者我可以有 2 个 fetchBaseQuery,一个用于 header,另一个用于刷新请求?

 const baseQuery = fetchBaseQuery({
    baseUrl: 'https://xr1.bernetco.ir/api/v1/',
    prepareHeaders: (headers, { getState }) => {
        const user = (getState() as RootState).user.currentUser

        if (user) {
            headers.set('Authorization', `Bearer ${user.token.access}`)
        }
        return headers
    },
    credentials: 'include', // This allows server to set cookies
})

const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
    args,
    api,
    extraOptions
) => {
    let result = await baseQuery(args, api, extraOptions)
    if (result.error && result.error.status === 401) {
        // try to get a new token

        const user = (api.getState() as RootState).user.currentUser
        const refreshResult = await baseQuery(
            { url: '/refresh-token/', method: 'POST', body: { refresh: user.token.refresh ?? '' } },
            api,
            extraOptions
        )
        
        
        const response = refreshResult.data as any
        if (response) {
            // store the new token
            api.dispatch(setCurrentUser(response.result))
            // retry the initial query
            result = await baseQuery(args, api, extraOptions)
        } else {
            api.dispatch(setCurrentUser(null))
        }
    }
    return result
}

prepareHeaders 也通过了 api.endpoint,所以你可以在那里做个例外:

 const baseQuery = fetchBaseQuery({
    baseUrl: 'https://xr1.bernetco.ir/api/v1/',
    prepareHeaders: (headers, { getState, endpoint }) => {
        const user = (getState() as RootState).user.currentUser

        if (user && endpoint !== 'refresh') {
            headers.set('Authorization', `Bearer ${user.token.access}`)
        }
        return headers
    },
    credentials: 'include', // This allows server to set cookies
})

当然,你也必须这样称呼它:

        const refreshResult = await baseQuery(
            { url: '/refresh-token/', method: 'POST', body: { refresh: user.token.refresh ?? '' } },
            { ...api, endpoint: 'refresh' },
            extraOptions
        )