Shaddix / react-query-swagger

Generates react-query hooks based on Swagger API definitions
MIT License
122 stars 4 forks source link

JSON.Parse throw error, even if response is correct object #17

Closed proggarapsody closed 1 year ago

proggarapsody commented 1 year ago
SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)
    at processLogin (Client.ts?ac1b:66:15)
    at eval (Client.ts?ac1b:48:10)

изображение изображение resultData200 value is

{
    "data": {
        "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXNoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBZG1pbiIsImV4cCI6MTY3NTE0NTUxMSwiaXNzIjoiYWxmX2lkZW50aXR5IiwiYXVkIjoiYWxmX2FwcCJ9.rkxfEfO3g1iZgO4FBUXuhLXP8H9axOiq-CTlQexJHZc",
        "expirationAt": "2023-01-20T06:11:51.615097Z"
    },
    "errors": [],
    "status": 200
}

i don't understand why Json.parse can't parse this object, any thoughts?

Shaddix commented 1 year ago

the data you posted is indeed a valid JSON.

The thing is, JSON.parse expects a string as an argument. But according to the error message, the first argument that you passed is an already parsed Object, not a string.

So, somehow, response.data is already an object, while we expect a string. Maybe you are parsing the data via some interceptor?

Posting the full sample could help :)

proggarapsody commented 1 year ago

@Shaddix I use only interceptor to request which add access token

client.interceptors.request.use(async (config) => {
  const token = authStore.getState().getAccessToken()

  // eslint-disable-next-line unicorn/prefer-ternary
  if (config.method === 'GET' || config.method === 'get') {
    config.withCredentials = false
  } else {
    config.withCredentials = true
  }

  client.defaults.headers.common.Authorization = `Bearer ${token}`
  config.headers.Authorization = `Bearer ${token}`

  return config
})

and to response to handle 401 error


client.interceptors.response.use(undefined, async (config) => {
  if (config?.response?.status === 401) {
    await refreshToken()
    client(config.request)
  }
})

I don't use any transformResponse functions

proggarapsody commented 1 year ago

@Shaddix In this interceptor I didn't return error reject


client.interceptors.response.use(undefined, async (error) => {
  if (error?.response?.status === 401) {
    await refreshToken()
    client(error.request)
  }
return Promise.reject(error.response)
})

This code fixed my problem I close the issue