1

我在使用此查询时遇到问题,它说这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;

在此处输入图像描述

4

1 回答 1

2

这是因为该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
  },
})
于 2021-10-04T16:12:49.637 回答