开发者问题收集

redux-toolkit prepareHeaders 不是一个函数

2021-10-04
1797

我在使用此查询时遇到问题,它说 prepareHeaders 不是一个函数,但我将其添加为一个对象,如下面的代码所示:

const access_token = localStorage.getItem('rs_access_token');
// Define a service using a base URL and expected endpoints
export const lfApi = createApi({
    reducerPath: 'lfApi',
    baseQuery: fetchBaseQuery({
        baseUrl: 'http://homestead.test/api/v1',
        prepareHeaders: {
            'Authorization': `Bearer ${access_token}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
    }),
    endpoints: (builder) => ({
        getUser: builder.query({
            query: (params) => `user`,
        }),
        getAgent: builder.query({
            query: (params) => `myagents/agents/${params}`,
        }),
    }),
});

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetUserQuery } = lfApi;
export const { useGetAgentQuery } = lfApi;

在此处输入图像描述

1个回答

这是因为 prepareHeaders 属性(如错误消息所示)接受的是函数,而不是对象。您可以从 此处 的示例中看到。

const baseQuery = fetchBaseQuery({
  baseUrl: '/',
  prepareHeaders: (headers, { getState }) => {
    headers.set('Authorization', `Bearer ${access_token}`);
    headers.set('Content-Type', 'application/json');
    headers.set('Accept', 'application/json');

    return headers
  },
})
NearHuscarl
2021-10-04