状态 204 显示 response.ok
Status 204 shows response.ok
在我的 ASP.NET 核心 API 后端,当没有数据时我发送 Status 204
但我注意到在前端,我的 fetch
调用仍然显示 response.ok
.
两个问题:
- 这是正常现象吗?我想,这是一个成功的呼叫,所以响应可能还可以,但它让我失望了。
- 检查
Status 204
的最佳方法是什么?
我的 React/Redux
应用程序中的当前代码如下所示:
export const apiCall = () => {
return (dispatch) => fetch("/api/get", fetchOptions)
.then((response) => {
if(response.ok) {
// Do something
} else {
// Couldn't get data!
}
})
};
这是我处理 fetch
调用的标准代码块。我应该如何修改它以处理 Status 204
场景?
除了可以查看Response.ok
,还可以查看Response.status
。每 MDN:
The status read-only property of the Response interface contains the status code of the response (e.g., 200 for a success).
Response.ok
只是检查 status
属性 是否为 200-299。
因此,除了检查 ok
,您还可以:
if (response.status === 200) {
// Do something
} else if (response.status === 204) {
// No data!
} else {
// Other problem!
}
在我的 ASP.NET 核心 API 后端,当没有数据时我发送 Status 204
但我注意到在前端,我的 fetch
调用仍然显示 response.ok
.
两个问题:
- 这是正常现象吗?我想,这是一个成功的呼叫,所以响应可能还可以,但它让我失望了。
- 检查
Status 204
的最佳方法是什么?
我的 React/Redux
应用程序中的当前代码如下所示:
export const apiCall = () => {
return (dispatch) => fetch("/api/get", fetchOptions)
.then((response) => {
if(response.ok) {
// Do something
} else {
// Couldn't get data!
}
})
};
这是我处理 fetch
调用的标准代码块。我应该如何修改它以处理 Status 204
场景?
除了可以查看Response.ok
,还可以查看Response.status
。每 MDN:
The status read-only property of the Response interface contains the status code of the response (e.g., 200 for a success).
Response.ok
只是检查 status
属性 是否为 200-299。
因此,除了检查 ok
,您还可以:
if (response.status === 200) {
// Do something
} else if (response.status === 204) {
// No data!
} else {
// Other problem!
}