代码之家  ›  专栏  ›  技术社区  ›  OpenStack

获取调用的状态代码为500时无法读取响应

  •  -1
  • OpenStack  · 技术社区  · 1 年前

    我正在对一个服务进行restful调用,并获得500个状态代码。回复如下:

    {
        "error": true,
        "message": "Test error",
        data: null
    }
    

    我使用以下代码到JavaScript端读取错误,但无法达到预期的结果。

    fetch('your-api-endpoint')
      .then(response => {
        if (!response.ok) {
          return Promise.reject(response)
        }
        return response.json(); // or response.text() depending on the response content type
      })
      .then(data => {
        // Handle successful response data
        console.log(data);
      })
      .catch(error => {
              //How to read the actual response and print it ?
        });
      })
     
    

    我想读取响应并显示 message 所有物但这一承诺从未得到解决。请帮忙

    1 回复  |  直到 1 年前
        1
  •  1
  •   Phil    1 年前

    您可以检查的类型 error 如果是 Response ,通过取回尸体 .text() 或者如果你确定格式, .json()

    fetch('https://httpstat.us/500', {
      headers: {
        Accept: 'application/json',
      },
    })
      .then((response) => {
        if (!response.ok) {
          return Promise.reject(response)
        }
        return response.json();
      })
      .then(console.log)
      .catch((error) => {
        if (error instanceof Response) {
          return error.json().then((errData) => {
            console.error('Request failed:', errData);
          });
        }
        console.error(error); // generic error
      });