首页 > 解决方案 > 如果请求成功,axios 错误响应返回 undefined

问题描述

您好,我正在像这样使用带有 React 和 Redux 的 axios

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
                }
            })
        }


   })
}

并在成功请求后(返回 200 状态码)它给了我这个错误

未捕获(承诺中)类型错误:无法读取未定义的属性“数据”

最有趣的是,它只在发送 200 状态码后才给我这个错误。如果有错误消息,它工作正常。那么问题是什么?我添加了 CORS 标头,但它不起作用,当我添加if(err.response){ }并在这种情况下处理我的错误时,它也可以正常工作。所以我想知道这个问题

标签: javascriptaxios

解决方案


推荐阅读