javascript - fetch api 从服务器获取错误消息而不是通用消息

标签 javascript redux react-redux fetch-api redux-thunk

我正在使用 redux thunk 在操作中获取一些数据

function handleErrors(response) {
    console.log(response)
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

export const something = (var) => dispatch => {
    fetch(`${url}/something`, {credentials: 'include'})
    .then(handleErrors)
    .then(res => res.json())
    .then(res =>
        dispatch({
            type: SOMETHING,
            payload: res
        })
    )
    .catch(error => 
        dispatch({
            type: ERROR,
            payload: error
        })
    )

我的 express 服务器出现错误时返回“一些错误”

return res.status(500).send({ message: 'some error' });

当它获取错误 (500) 时,它的消息是通用的“内部服务器错误”。

我如何在抓取中得到“一些错误”?

最佳答案

不确定您的handleError 中有什么。提取错误消息的一种方法是这样的

fetch(url)
  .then(res => {
    // Check if response has errors
    if (res.ok) {
      // No errors
      return res.json();
    } else {
       // Has errors, since res.json() returns a Promise, we
       // chain a then here to get the value and return the err value
       // as Promise rejection so that it will go to the 
       // catch handler
       return res.json().then(err => Promise.reject(err));
       // this could also be
       // return res.json().then(err => throw Error(err));
    }
  })
  .then(json => {
    // dispatch success
  })
  .catch(err => {
    // dispatch error
  });

关于javascript - fetch api 从服务器获取错误消息而不是通用消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784371/

相关文章:

javascript - 窗口位置 - 只有协议(protocol)、主机名和路径名

c# - 如何使用 window.open() 传递变量?

javascript - Redux.js : catching malformed actions?

javascript - 在 redux 中调试 reducer 时遇到困难

javascript - react + 终极版 : submit multi-component form

javascript - 在某些情况下数组未填充

javascript - Nodejs http请求console.log函数打印两次

javascript - Jest enzyme 模拟 ('click' )以及事件对象和值

javascript - 用于填充 React 组件中下拉列表的多个 API 调用

Angular + redux/ngrx : state update vs. 形式