在特定端点禁用 RTK 查询 prepareHeaders

disable RTK Query prepareHeaders on specific endpoint

如何在特定端点上禁用 prepareHeaders?例如,我在登录或注册端点上不需要授权 header,但在某些端点上我需要授权 headers。

  export const backendService = createApi({
  reducerPath: 'backend',
  baseQuery: fetchBaseQuery({
    baseUrl: `${Endpoint}`,
    prepareHeaders: (headers, {getState}) => {
      const token = getState().auth.token;
      if (token) {
        headers.set('authorization', `Bearer ${token}`);
      }
      headers.set('Access-Control-Allow-Origin', '*');
      return headers;
    },
  }),
  tagTypes: ['Question', 'Questions'],
  endpoints: build => ({
    registerUser: build.mutation({ <------ skip prepareHeaders in register
      query: body => ({
        url: 'auth/local/register',
        method: 'POST',
        body,
      }),
    }),
    login: build.mutation({ <------- skip prepareHeaders on login
      query: body => ({
        url: 'auth/local',
        method: 'POST',
        body,
      }),
    }),
    getCategories: build.query({ <------ apply prepareHeaders 
      query: () => {
        return {
          url: 'categories'
        };
      },
    }),
    
  }),
});

RTK 1.7 的当前测试版将端点名称传递给 prepareHeaders,因此如果您尝试这样做,您应该能够解决这个问题。

The BaseQueryApi and prepareheaders args now include fields for endpoint name, type to indicate if it's a query or mutation, and forced to indicate a re-fetch even if there was already a cache entry. These can be used to help determine headers like Cache-Control: no-cache.