redux RTK查询从错误响应中获取状态代码和错误消息

txu3uszq  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(115)

我使用rtk查询与自定义baseQuery

const staggeredBaseQueryWithBailOut = retry(
  async (args: FetchArgs | string, api, extraOptions) => {
    try {
      const result = await fetchBaseQuery({
        baseUrl: config.apiBaseURL,
        prepareHeaders: (headers, api) => {
          const {
            auth: { token }
          } = api.getState() as RootState
          if (isCustomQuery(args) && args.url === config.authURL) {
            headers.set("Authorization", `Basic ${config.basicToken}`)
          } else {
            if (token) headers.set("Authorization", `Bearer ${token}`)
          }
        }
      })(args, api, extraOptions)
      if (result.error) throw result
      return result
    } catch (error) {
      return { error: error }
    }
  },
  {
    maxRetries: 2
  }
)

每当API调用失败时,API都会使用errorMessage进行响应。
我想得到errorMessage &&状态码。
从useQueryHook返回的错误对象是由rtk生成的,带有类似“FETCH_ERROR”的非描述性消息。
有办法绕过去吗?

ni65a41a

ni65a41a1#

它指出,问题是与CORS头不发回的情况下,错误的React。只是一个API问题,而不是rtk查询实现错误。

bfrts1fy

bfrts1fy2#

你为什么不这样试试

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { logout } from "./slice/authSlice";

const baseQuery = fetchBaseQuery({
// eslint-disable-next-line no-undef
baseUrl: `${process.env.REACT_APP_BASE_URL}`,
credentials: 'include',
prepareHeaders: (headers, { getState }) => {
    const token = getState().auth.token
    if (token) {
        headers. Set("authorization", `Bearer ${token}`)
    }
    return headers
 }
})

const baseQueryWithReauth = async (args, api, extraOptions) => {
let result = await baseQuery(args, api, extraOptions)

if (result?.error?.status === 403) {
    api.dispatch(logout())
    //console.log('sending refresh token')
    // send refresh token to get new access token 
   /* const refreshResult = await baseQuery('/refresh', api, extraOptions)
    console.log(refreshResult)
    if (refreshResult?.data) {
        const user = api.getState().auth.user
        // store the new token 
        api.dispatch(setCredentials({ ...refreshResult.data, user }))
        // retry the original query with new access token 
        result = await baseQuery(args, api, extraOptions)
    } else {
        api.dispatch(logout())
    }*/
}

  return result
}

export const api = createApi({
 baseQuery: baseQueryWithReauth,
 reducePath: "adminApi",
 tagTypes: ["User", "Auth", "Customers"],
 endpoints: (build) => ({

    //auth
    login: build. Mutation({
        query: (body) => ({
            url: `users/login`,
            method: 'POST',
            body,
        }),
        invalidatesTags: ['User'],
    }),
    logout: build. Mutation({
        query: (body) => ({
            url: `users/logout`,
            method: 'PUT',
            body,
        }),
        invalidatesTags: ['User'],
    }),
    register: build. Mutation({
        query: (body) => ({
            url: `users/register`,
            method: 'POST',
            body,
        }),
        invalidatesTags: ['User'],
    }),
 })
})

export const {  useLogoutMutation, useLoginMutation, useRegisterMutation } = api;

注意我选择错误result?.error?.status === 403的方式
我希望这能帮上忙。

相关问题