Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在JS'中解析非200状态代码中的JSON;什么是获取API?_Javascript_Http Headers - Fatal编程技术网

Javascript 如何在JS'中解析非200状态代码中的JSON;什么是获取API?

Javascript 如何在JS'中解析非200状态代码中的JSON;什么是获取API?,javascript,http-headers,Javascript,Http Headers,我的取回请求如下- fetch(base_url + "/user/details", options) .then(response => { if (response.ok) { return response.json(); } else { throw new Error(response.json().message); } })

我的取回请求如下-

fetch(base_url + "/user/details", options)
      .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error(response.json().message);
        }
      })
      .then(responseJson => processResponse(responseJson))
      .catch(error => handleError(error));
当响应不是
ok
(本例中为400)时,JSON如下所示-

{"timestamp":"2020-08-27T14:44:21.077176","message":"Failed for some reason."}
但是,当我尝试访问上面的响应时(如-
response.json().message
),我得到一个空白

在这种情况下如何访问JSON?

response.JSON()
返回一个承诺

它没有
消息
属性,只有它的解析值有



这就解释了丢失的消息值。那么,我如何访问它呢?就像处理任何承诺一样,返回
response.json()
,然后在下一篇
Then
中阅读它。(我倾向于重写东西来使用
async
/
await
,因为我发现这样更容易理解)。你能写一些代码来解释一下吗?我不明白如何添加
然后在
catch
中添加
const response = await fetch(base_url + "/user/details", options);
const data = await response.json();
if (response.ok) {
    return processResponse(data);
}
handleError(new Error(data.message));