redux 如何将对象传输到头fetchBaseQuery

wwwo4jvm  于 2022-11-24  发布在  Hbase
关注(0)|答案(1)|浏览(261)

我正在使用电影的api,为了创建一个对服务器的请求,我需要将它传递给header对象

{
    'X-API-KEY': 'there is apikey',
    'Content-Type': 'application/json',
}

我使用RTK查询发出请求

export const filmsApi = createApi({
reducerPath: 'awaitsFilms',
baseQuery: fetchBaseQuery({
    baseUrl: url,
}),
endpoints: (build) => ({
    getAwaitsFilms: build.query({
        query: () => `top?type=TOP_AWAIT_FILMS`,
    }),
}),

})
如何将这个头对象传递给fetchBaseQuery?

busg9geu

busg9geu1#

文件

import type { RootState } from './store'

const baseQuery = fetchBaseQuery({
  baseUrl: '/',
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as RootState).auth.token

    // If we have a token set in state, let's assume that we should be passing it.
    if (token) {
      headers.set('authorization', `Bearer ${token}`)
    }

    return headers
  },
})

相关问题