Home > database >  React Axios Uncaught (in promise)
React Axios Uncaught (in promise)

Time:02-11

Currently I am trying to receive data from an API with Axios, which gives me an Uncaught (in promise). There is no further information in the error message.

Dashboard.tsx:

Axios.get("/WeatherForecast/Get").then(response => {
        console.log("success");
        console.log(response);
    }).catch((exception) => {
        console.log(exception);
    });

axiosConfig.ts:

import axios from "axios";
import { URL_API } from "./config/config";

export const configAxios = () => {
axios.defaults.baseURL = URL_API;

axios.interceptors.response.use(function (response) {
    if (response.data) {
        // return success
        if (response.data.status === 200 || response.data.status === 201) {
            return response;
        }
        // reject errors & warnings
        return Promise.reject(response);
    }

    // default fallback
    return Promise.reject(response);
}, function (error) {
    // if the server throws an error (404, 500 etc.)
    return Promise.reject(error);
});
}

Response in console: enter image description here

CodePudding user response:

Update your interceptor to target response.status instead of response.data.status. Per the response schema response.data will provide you the numeric status code that you can do you conditional checks against:

import axios from "axios";
import { URL_API } from "./config/config";

export const configAxios = () => {
  axios.defaults.baseURL = URL_API;

  axios.interceptors.response.use(
    function (response) {
      if (response.data) {
        // return success
        if (response.status === 200 || response.status === 201) {
          return response;
        }
        // reject errors & warnings
        return Promise.reject(response);
      }

      // default fallback
      return Promise.reject(response);
    },
    function (error) {
      // if the server throws an error (404, 500 etc.)
      return Promise.reject(error);
    }
  );
};
  • Related