- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用后端 API,它针对同一端点的不同请求返回不同的数据类型。虽然更合适的解决方案是统一返回的数据类型,但遗留问题、时间和缺乏测试对这个解决方案不利。
我正在集中我的 call
方法,以供需要调用端点的应用程序的其他部分使用。这个call
方法实现了fetch。欲了解更多信息:
export default function call<P> (method: TCallMethod, payload: P, parameter?: string): Promise<IServerResponseObject> {
const url: string = buildUrl(parameter);
const body: string | null = payload ? JSON.stringify(payload) : null;
return fetch(url, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthToken()}`
},
body
}).then(async (response) => {
let body: IServerResponseObjectBody = {
message: '',
code: ''
};
if (response) {
body = await response.json();
}
return {
status: response.status,
body
};
});
}
当我接收数据时,我使用 Response.json
方法对其进行解码。
if (response) {
body = await response.json();
}
问题是有时我没有收到任何数据(当用户未经身份验证时 - 尽管这是一种边缘情况)或者服务器仅响应一个 bool 值。
在这种情况下,json()
执行会失败,因为我们没有处理 JSON 数据。
即:
FetchError: invalid json response body at http://localhost:4545/api/definition/isNameUnique/used%20name reason: Unexpected end of JSON input
我想知道是否有比嵌套 try/catches
更干净的方法来确定从可用的解码方法中使用哪种解码方法: https://developer.mozilla.org/en-US/docs/Web/API/Body#Methods
这感觉像是一个潜在的解决方案:https://developer.mozilla.org/en-US/docs/Web/API/Body#Properties但文档不太明确,并且缺乏如何使用它的示例。
最佳答案
在我看来,您想使用 text
来读取响应,然后查看生成的文本并决定要做什么。 大致:
const text = await response.text();
if (!text) {
// no response, act accordingly
} else if (reBool.test(text)) {
// boolean response, determine whether it's true or false and act on it
} else {
// JSON response, parse it
data = JSON.parse(text);
// ...then use it
}
...其中 reBool
是一个正则表达式,用于测试服务器有时返回的 bool 值,例如 /^(?:true|false)$/i
.
如果响应可能有空格,您可以 trim
response.text()
的结果。
您可能还想做一些不相关的事情:
您没有检查是否有成功的响应(这是很多人都会犯的错误,所以我把很多人都写在了我原本贫乏的小博客上)。在使用 json
或 text
等之前检查 response.ok
。
将 async
函数作为回调传递给 then
没有多大意义。如果您要使用async
,请尽早执行,将call
设为async
函数,然后使用await
贯穿整个正文,而不是混合你的隐喻......
解决这些问题并折叠在上面的主要答案中(您需要根据需要进行调整,IServerResponseObject
需要更改,或者您需要对 bool 响应执行不同的操作):
const reBool = /^(?:true|false)$/i;
export default async function call<P> (method: TCallMethod, payload: P, parameter?: string): Promise<IServerResponseObject> {
const url: string = buildUrl(parameter);
const body: string | null = payload ? JSON.stringify(payload) : null;
const response = await fetch(url, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthToken()}`
},
body
});
const {status} = response;
if (!response.ok) {
throw new Error("HTTP error " + status); // Or `return {status};` or similar, but making it an error is useful
}
const text = (await response.text()).trim();
let result = {status};
if (!text) {
// blank, act accordingly, perhaps:
result.body = null;
} else if (reBool.test(text)) {
result.body = text === "true";
} else {
result.body = JSON.parse(text);
}
return result;
}
关于javascript - 动态决定使用哪种 Fetch 响应方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53762388/
这是一道函数依赖题。 我知道当 x->yz 然后 x->y 和 x->z 时。但是上面的依赖关系可能吗? 最佳答案 If xy determines z can x determine z and y
我有一个奇怪的问题。 Line 61: $this->_currentRoute = Default_Model_Routes::getInstance()->getCurrentRoute(); .
我正在开发一种工具来比较两个波形文件的波形相似性。例如,我有一个持续时间为 1 分钟的波形文件,我使用第一个波形文件制作了另一个波形文件,但每 5 秒生成一次数据,间隔为 5 秒至 0。 现在我的软件
我遇到了一个奇怪的问题,尽管我打赌有一个巧妙的方法可以解决它。 情况是我有一个具有三列排序状态的表:完全未排序,在这种情况下我不希望出现任何图标,按升序排序,在这种情况下我想要一个向上箭头,以及按降序
Java 语言规范提供了criteria用于确定(格式良好的)执行是否满足“Java 内存模型的因果关系要求”。让我们假设执行是有限的。我试图了解是否存在多项式时间算法来证明或反驳这种情况。 真的,我
Java 语言规范提供了criteria用于确定(格式良好的)执行是否满足“Java 内存模型的因果关系要求”。让我们假设执行是有限的。我试图了解是否存在多项式时间算法来证明或反驳这种情况。 真的,我
我正在编写一个简单的Bank类,其中包含Account。我希望人员能够开设一个新的受密码保护的银行帐户,并从其帐户中提取和存入资金。账户设在银行内。银行和帐户类应提供哪些服务? 假设 p 已在银行 b
我的标题概括了这一点。我有一个将要开发的简单业务线应用程序,并且很好奇如何确定我应该针对哪个 .NET 版本。支持 Win XP SP3 会很好,但不是必需的。它将用于索引多页 tiff,因此导入一批
已锁定。这个问题及其答案是locked因为这个问题是题外话,但却具有历史意义。目前不接受新的答案或互动。 你是否真的“尝试过”(意味着在其中编程,而不仅仅是阅读有关它的文章)Erlang并决定在项目中
我正在尝试使用 ExceptionFilterAttribute 为 Web Api 实现异常处理。我已经继承了ExceptionFilterAttribute 类并覆盖了onException 方法
前一段时间在一次编程比赛中我遇到了一个令人费解的问题,此后一直困扰着我。虽然我没有逐字记住,但我会尽力重现: Jack starts at 0 on the number line and jumps
我有什么: 我有一个主要内容区域,后面跟着两个旁白: #primary,#secondary,#tertiary{float:left; width:33%;} Primary
我无法正确操作键盘。 整个 View 充满了文本字段。 当我使用通知将 View 向上移动时,上方的文本框不再可见: override func viewDidLoad() { super.v
已结束。此问题正在寻求书籍、工具、软件库等的推荐。它不满足Stack Overflow guidelines 。目前不接受答案。 我们不允许提出寻求书籍、工具、软件库等推荐的问题。您可以编辑问题,以便
我在尝试获取父对象来过滤子事件时遇到问题。 在下面的示例中,我在旋转框上设置了一个事件过滤器。事件过滤器检测旋转框上的鼠标按下事件。然后,我希望父对象根据某些标准接受或忽略该事件。 问题是它似乎接受了
我使用从 std::system_error 继承的类进行错误处理,我想控制调用 what() 时返回的内容。原因:标准(C++11 和 C++1y CD 草案 - N3690,下面的 § 引用是后者
我正在用 Swift 构建一个 iOS 应用程序,它的起始页有 6 个按钮。这些按钮中的每一个都将连接到一个 TableView Controller ,其数据由 NSFetchedResultsCo
我想构建这样的东西 数据存储| mycode.py | RESTful API | mywebapp.py(Django 或 Tornado) 我检查了 Django 的 Piston,但似乎这样我就
究竟如何更改 RichTextBox 中的字体? 环顾四周给了我似乎不再有效的旧答案。我认为这就像执行 richtextbox1.Font = Font.Bold; 或类似操作一样简单。原来不是,所以
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 7 年前。 Improve this qu
我是一名优秀的程序员,十分优秀!