首页 > 解决方案 > 未处理的拒绝(TypeError):无法读取未定义的属性“statusText”

问题描述

我在尝试使用 react-redux 实现删除功能时遇到了这个问题。

在此处输入链接描述

动作/profile.js

export const deleteExperience = id => async dispatch => {
  try {
    const res = await axios.delete(`/api/profile/experience/${id}`);

    dispatch({
      type: UPDATE_PROFILE,
      payload: res.data
    });

    dispatch(setAlert("Experience Removed", "success"));
  } catch (err) {
    dispatch({
      type: PROFILE_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status }
    });
  }
};

减速器/profile.js

case UPDATE_PROFILE:
  return {
    ...state,
    profile: payload,
    loading: false
  };
case PROFILE_ERROR:
  return {
    ...state,
    error: payload,
    loading: false
  };

标签: javascriptreact-redux

解决方案


问题出在删除 API 中。API应该像这样工作http://localhost:5000/api/profile/experience/5df8f54012b7a81ac04d6b25但不知何故它也以这种方式工作http://localhost:5000/api/profile/experience/5d与用户的令牌。所以我改变了api代码

try {
    const profile = await Profile.findOne({ user: req.user.id })
    const removeIndex = profile.education.map(item => item.id).indexOf(req.params.edu_id)
    profile.education.splice(removeIndex, 1)

    await profile.save()
    res.json({ msg: 'Education Deleted'})
} catch (err) {
    console.log(err.message)
    res.status(500).send('Server Error')
}

try {
    const foundProfile = await Profile.findOne({ user: req.user.id });
    const eduIds = foundProfile.education.map(edu => edu._id.toString());
    const removeIndex = eduIds.indexOf(req.params.edu_id);
    if (removeIndex === -1) {
        return res.status(500).json({ msg: "Server error" });
    } else { 
        foundProfile.education.splice(removeIndex,1);
        await foundProfile.save();
        res.json({ msg: 'Education Deleted'})
    }
} catch (error) {
    console.error(error);
    return res.status(500).json({ msg: "Server error" });
}

现在它工作正常。


推荐阅读