Search code examples
reactjsrtk-query

Why RTK-Query always return originalStatus 200?


There is not backend on my localhost:3000 and I expect that all of my requests will return error 404. But RTK-Query always returns this:

{
  data: "<!DOCTYPE html>\n<html lang=\"ru\">\n  <head>\n    <meta c..."
  error: "SyntaxError: Unexpected token < in JSON at position 0"
  originalStatus: 200
  status: "PARSING_ERROR"
}

Data contains root page html, originalStatus always 200. Screen

My api.ts:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import getCookie from '../../utils/get-cookie'

export const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: '/',
    prepareHeaders: (headers) => {
      const token = getCookie('csrftoken')

      if (token) {
        headers.set('X-CSRFToken', token)
      }

      return headers
    },
  }),
  endpoints: () => ({}),
})

My getUserEndpoint.ts:

import { api } from './api'
import { IUserInitialState } from '@types'

interface IGetUserResponse {
  ...some types
}

const getUserEndpoint = api.injectEndpoints({
  endpoints: (build) => ({
    getUser: build.query<IGetUserResponse, void>({
      query: () => ({
        url: 'user/',
      }),
    }),
  }),
})

export const {
  useGetUserQuery,
  endpoints: { getUser },
} = getUserEndpoint

In App.ts I use hook:

const {
  data,
  isError: isGetUserError,
  error: getUserError,
  isFetching: isFetchingUser,
} = useGetUserQuery()

As a result I expect originalStatus 404, because there is no connection to any server on my local machine, but I always get originalStatus 200 and root page html in data. Please help me figure it out


Solution

  • It makes a connection to http://localhost:3000/user and that returns a status of 200 and some HTML content.

    Then it fails to parse that HTML content and gives you a parsing error, with originalStatus: 200 - which is the HTTP status it got from the server - in your screenshot.

    Why would you expect it to suddenly be 404? And where would that come from? All it knows is it gets a string that is not JSON.

    Generally as to how to "fix" this: go through your server code so it returns an actual 404 - this does not seem to be a RTK-Query problem.