Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token:

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

export const refreshApi = createApi({
  reducerPath: "apiSlice",
  baseQuery: fetchBaseQuery({
    baseUrl: `${process.env.NEXT_PUBLIC_SERVER_URL}`,
    credentials: "include",
  }),
  endpoints: (builder) => ({
    refreshAuthorization: builder.query({
      query: () => "/api/auth/refresh",
    }),
  }),
});

export const { useRefreshAuthorizationQuery } = refreshApi;

This is the response I expect from my server:

    return res
        .cookie("accessToken", accessToken, {
           httpOnly: true,
           secure: config.get("isSecure"),
           sameSite: "none",
      })

However, I encountered this error: https://i.sstatic.net/bNkwB.png

It appears that the front-end is expecting JSON but I am only returning a status.

Answer №1

Indeed, the fetchBaseQuery function in Redux-Toolkit Query assumes JSON responses by default. It seems that the cookie response content type is "text/html." To handle this, you can customize the response handler for specific endpoints.

Here's an example:

export const refreshApi = createApi({
  reducerPath: "apiSlice",
  baseQuery: fetchBaseQuery({
    baseUrl: `${process.env.NEXT_PUBLIC_SERVER_URL}`,
    credentials: "include",
  }),
  endpoints: (builder) => ({
    refreshAuthorization: builder.query({
      query: () => ({
        url: "/api/auth/refresh",
        responseHandler: "text",
        // or
        // responseHandler: response => response.text();
      }),
    }),
  }),
});

For more information, you can refer to Individual Query Options, specifically Parsing a Response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to omit type arguments in TypeScript when they are not needed?

Here is a function I am currently working with: function progress<T>(data: JsonApiQueryData<T>): number { const { links, meta } = data.getMeta(); if (!links.next) { return 1; } const url = new URL(links.next); return parseInt(url ...

Join the Observable and formControl in Angular 4 by subscribing

My goal is to display the data retrieved from FireStore in the screen fields upon loading. However, the buildForm() function is being called before subscribing to the data, resulting in the failure to populate the screen fields with the FireStore data. pe ...

Having trouble with CSRF validation while using Django Rest and Vue.js with Axios?

When trying to integrate Django Rest Framework with VueJS and Axios, I consistently encounter the following error message: "CSRF Failed: CSRF token missing." Despite my frontend header appearing to be correct and the cookie loading correctly into the head ...

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: I'm curious, how can I implem ...

The functionality of TypeScript's instanceof operator may fail when the method argument is not a simple object

There seems to be an issue with a method that is being called from two different places but returns false for both argument types. Despite checking for the correct types, the problem persists and I am unsure why. Although I have read a similar question on ...

The metadata for Company#companyTypesLinks could not be located. Please verify that the entity object has been correctly specified

I am facing an issue with the relationship between my entities. I have tried everything, but I still encounter the same problem. Here are my scripts: Company.entity.ts export class Company extends AppBaseEntity { @Column('text', { name: ' ...

Challenges in Power BI Custom Visual Development: Trouble setting height for div elements

Currently, I am working on creating a custom visual for Power BI that includes a leaflet map within a div element. However, the issue arises when I fail to set a specific height for the map, resulting in an empty visual. I have managed to set a fixed heigh ...

Looking for a way to activate a button that triggers the drag animation (translateX) for card demonstrations?

Here is the situation I am dealing with: I am in need of a feature similar to Tinder, where I can initiate the same transition as dragging. Specifically, I am attempting to implement like and dislike button functionality similar to Tinder. However, due t ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

An error occurred while trying to create a new instance using prisma.model.create. The argument `school_id` provided in data.subjects.create.2.school_id is not recognized for

My dilemma revolves around these two models: model School { id Int @id @default(autoincrement()) name String? center_no Int? type String? subjects SubjectPool[] } model SubjectPool { id Int @id @default(a ...

How can we add a key:value pair at a specific position in an array in Angular 2 using Typescript?

Is there a way to insert a key value pair at a specific index in an array? I am currently struggling with this task. Here is the code I have been working on: this.quiz.push( { "question-no":this.no, "Ans":this.ans } I require this functionality to ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

What are the steps to avoid TypeScript from automatically installing and referencing its own @types in the AppDataLocal directory?

I'm encountering a perplexing issue where it appears that TypeScript is setting up its own version of React in its unique global cache system (not entirely sure what to call it? presuming that's the case) and utilizing it within my project. In p ...

typescript provides an asynchronous recursive mapping function that allows for changing parent data starting from the leaf node

I am currently facing a challenge in identifying the leaf node within a non-binary tree that requires modification. The process involves computing a blake2b hash from the leaf data, passing it to the parent node, and repeating this calculation until reachi ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

Error: The property 'count' cannot be destructured from '(0, react_redux__WEBPACK_IMPORTED_MODULE_3__.useSelector)(...)' because it is not defined

After watching this helpful tutorial: https://www.youtube.com/watch?v=iBUJVy8phqw I attempted to incorporate Redux into my Next.js app, following the steps outlined. However, I encountered a roadblock and can't figure out why. I've double-checke ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...

Steps for activating the read-only input field

Currently, I have an input box in ng Ant design with the readonly attribute. I want to make it editable once the user clicks on edit. Can someone guide me on how to achieve this? Snippet of Code: <i nz-icon type="edit" class="toolbar-icon" (click)="ed ...

Issue detected: Props that are of type Object/Array must utilize a factory function in order to provide the default value

I recently started using Vue-Cli3.0 and came across this interesting module for Vue.js called https://github.com/holiber/sl-vue-tree It's a customizable draggable tree component for Vue.js, but I encountered an issue where it couldn't copy funct ...