我如何使用Redux RTK查询与aws API或集成RTX与Aws cognito json令牌?

tf7tbtn2  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(142)

我正在尝试将RTK查询与aws API请求集成在一起。我不需要使用API请求,但我需要使用Cognito提供的身份验证。
我试着整合这种方式,但显然不好惹的是又补充道:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

// Define a service using a base URL and expected endpoints
export const researchApi = createApi({
    reducerPath: 'researchApi',

    baseQuery: fetchBaseQuery({ baseUrl: process.env.NEXT_PUBLIC_API_RESEARCH }),

    prepareHeaders: async (headers) => {
        headers.set('Authorization', (await Auth.currentSession()).getIdToken().getJwtToken());
        return headers;
    },

    endpoints: (builder) => ({
      getResearch: builder.query({
        query: () => `research`,
      }),
    }),
  })

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

有什么想法如何使这两者一起工作吗?无论是用awsapi发送请求,还是一种将json令牌传递给请求的方法都可以工作。
干杯干杯干杯

iyr7buue

iyr7buue1#

所以我做的prepareHeaders是错误的,下面是一些工作代码:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { Auth, API, Storage } from 'aws-amplify';

// Define a service using a base URL and expected endpoints
export const researchApi = createApi({
    reducerPath: 'researchApi',

    baseQuery: fetchBaseQuery({ 
        baseUrl: process.env.NEXT_PUBLIC_API_RESEARCH,
        prepareHeaders: async (headers, { getState }) => {
            const token = (await Auth.currentSession()).getIdToken().getJwtToken();
            headers.set('Authorization', `${token}`);            
            return headers;
        }
    }),
    endpoints: (builder) => ({
      getResearch: builder.query({
        query: () => `research`,
      }),
    }),
  })

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

相关问题