fetch api 从服务器获取错误消息而不是一般消息

fetch api get error messages from server rather than generic messages

我正在使用 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 服务器出错时响应 'some error'

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

当它获取错误 (500) 时,它的消息是通用的 "Internal Server Error"。

如何在 fetch 中获取 'some error'?

不确定你的 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
  });