简体   繁体   中英

Handling 302 status with RTK Query

I have a POST request which returns a 302 when successful. I need to get the location response header which holds the url I'll need to redirect to. Currently I have this:

accountLogin: builder.mutation<any, any>({
   query: (body) => ({
      url: `/accounts/login`,
      method: 'POST',
      body,
      responseHandler: (response) => {
        console.log(response, response.headers);
        return response.text();
      },
  }),
}),

If I look in the.network tab of my browser the 302 is there, as is the location header with the proper URL. But the 'console.log' in responseHandler shows no headers. I can't find much about this in the documentation -- what am I missing?

to access status code you can use validateStatus something like this:

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

export const customApi = createApi({
  // Set the baseUrl for every endpoint below
  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => ({
        url: `users`,
        // Example: we have a backend API always returns a 200,
        // but sets an `isError` property when there is an error.
        validateStatus: (response, result) =>
          response.status === 200 && !result.isError,
      }),
    }),
  }),
})

or use transformResponse

transformResponse: (response, meta, arg) =>
  response.some.deeply.nested.collection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM