首页 文章

获取Api javascript错误时会收到JSON

提问于
浏览
-1

我使用fetch将数据发布到服务器:

fetch(url, {
    method: 'post'
  })
  .then(status)
  .then((data) => {
    console.log(data);
  }).catch((error) => {
    console.log('error: ' + error);
  });
});

这是状态方法

const status = (res) => {
  console.log(res);
  if(res.status >= 200 && res.status < 300) {
    return Promise.resolve(res.json());
  } else {
    return Promise.reject(res.json());
  }
}

如果代码是200,那么它工作正常(我收到我的JSON) . 但如果不是,我会 grab 错误并记录下来 . 它显示未经授权但我希望我收到我的错误JSON . 像这样的东西

{ 
 "status": 400,
 "error": "pass is not corret"
}

我怎样才能发现我的Json错误?

2 回答

  • 0

    在这一点上,我认为你只需要从响应中返回JSON . 无论你是否在返回JSON,你的条件判断?:

    const status = (res) => {
      console.log(res);
      if (res.status >= 200 && res.status < 300) {
        return res.json();
      }
    }
    
  • 0

    res.json() 返回 Promise . 当你拨打 Promise.reject 时,你只能通过拒绝理由 . 就像字符串,对象或错误一样,描述了你拒绝的原因 .

    我会将代码更改为

    const status = (res) => {
      return new Promise((resolve, reject) => {
        res.json().then((json) => {
          if(res.status >= 200 && res.status < 300) {
            resolve(json);
          }
          else {
            reject(json)
          }
        });
      });
    }
    

    资源:

相关问题