我想检查我的端点是否返回 404 错误状态以及主体是否具有某些属性。 GotJS 支持 JSON 模式,它会自动解析正文,但那时我没有 HTTP 属性。我可以以某种方式将它结合起来吗?还是我需要自己解析JSON?我尤其不明白该方法 json()
一旦有效,然后就未定义了。
测试
data = await bff("polls/abc").json();
console.log(data);
console.log(data.success);
response = await bff("polls/abc");
console.log(response.body);
console.log(response.json());
输出
console.log test/polls.int.test.js:96
{ success: false }
console.log test/polls.int.test.js:97
false
console.log test/polls.int.test.js:99
{"success":false}
TypeError: response.json is not a function
为什么这两个变体不等效?
await bff("polls/abc").json()
和
response = await bff("polls/abc");
response.json();
更新:bff 定义
const bff = got.extend({
prefixUrl: "http://localhost:3000/bff/",
throwHttpErrors: false,
headers: {
"content-type": "application/json; charset=utf-8'"
},
});
Cengel 的解决方案
response = await bff("polls/abc", { responseType: 'json' });
console.log(response.body.success);
console.log(response.statusCode);
console.log test/polls.int.test.js:98
false
console.log test/polls.int.test.js:99
404
最佳答案
你做不到
response = await bff("polls/abc");
response.json();
因为json()
function 是一个异步函数,就像 bff
,并且它返回一个 promise 并且也必须等待。
了解为何调用 await bff("polls/abc").json()
有效,我们必须剖析它。首先,await
正在不等待bff("polls/abc")
(返回一个 Promise)但是调用 json()
.
但是等等:如果 bff()
返回一个 Promise,为什么bff().json()
工作?不应该bff()
必须先等待吗?
got
中的一行文档可能会给出答案:
The promise also has .text(), .json() and .buffer() methods which return another Got promise for the parsed body.
所以 bff()
返回的 Promise实际上并不是一个“真正的”Promise,但具有这三种方便的方法,因此您不必等待 bff()
如果您只获得 JSON 格式的响应,也是如此。但由于您实际上也想查看响应本身,因此您应该执行以下操作:
const promise = bff("polls/abc");
const response = await promise;
const data = await promise.json();
if (response.status === 404) {
...
}
另一种方法似乎是设置 responseType
到“json”,它应该自动将正文转换为 JSON,因此您不必调用 json()
完全手动,只需使用:
const response = await bff("polls/abc", { responseType: 'json' });
if (response.status === 404) {
// use response.body to access the converted json
}
关于javascript - GotJS - 获取响应属性和 JSON 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287768/