【问题标题】:fetch api get error messages from server rather than generic messagesfetch api 从服务器获取错误消息而不是通用消息
【发布时间】:2018-09-21 21:18:20
【问题描述】:

我正在使用 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
        })
    )

我的快递服务器出现错误时响应“一些错误”

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

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

如何在 fetch 中获取“一些错误”?

【问题讨论】:

  • 试试这个 github.com/github/fetch/issues/203#issuecomment-143347675

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


【解决方案1】:

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

【讨论】:

  • 你可以用这个答案上的第一个then替换你的handleError函数并删除你的.then(res) => res.json()
  • 你能解释一下你的代码是如何得到实际响应的,而不是通用的吗?
  • 更新了我的答案以包含一些解释。希望有帮助
  • @totalnoob 有不清楚的地方告诉我,否则请采纳
  • @jpdelatorre 当我在上面申请时,我收到“未捕获(承诺)语法错误:JSON 输入意外结束”的错误。我该如何解决这个问题
猜你喜欢
  • 2021-07-06
  • 1970-01-01
  • 2011-06-26
  • 2016-03-12
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
相关资源
最近更新 更多