'axios error response returns undefined if request is successful

Hello i am using axios with React & Redux like this

export const addCustomer = ({destructured data}) => dispatch => {
    axios.post('/api/customer-base/add-customer', {
        //data
    })
    .then(res => res.data)
    .then(data => {
        console.log(data)
        dispatch({
            type: ADD_CUSTOMER,
            payload: {
              newCustomer: data.newCustomer
            }
        })
    })
    .catch(err => {
        if(err.response.data.message){
            console.log(err.response.data.message)
            dispatch({
                type: ADD_CUSTOMER_ERROR,
                payload: {
                   error: err.response.data.message
                }
            })
        }


   })
}

and after successful request (returning 200 status code) it gives me this error

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

the most interesting thing is that it only gives me this error after sending 200 status code. if there is error message it works fine. so what is problem? i added CORS header but it did not work and when i add if(err.response){ } and inside this condition i handle my error it also works fine. so i want to know the problem



Solution 1:[1]

Maybe you need to add "config" to your post request:

dispatch({ type: ADD_CUSTOMER_REQUEST });
const config = {
  headers: {
    "Content-Type": "application/json",
  },
};
const { data } = await axios.post("/api/customer-base/add-customer", ThatdestructuredData*, config);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anas Hamadi