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));