GotJS - 获取响应属性和 JSON 正文

GotJS - get both response attributes and JSON body

我想检查我的端点 returns 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() 函数是一个异步函数,就像 bff 一样,它 returns 也是一个 promise,也必须等待。

要理解调用 await bff("polls/abc").json() 的原因,我们必须剖析它。首先,awaitnot waiting bff("polls/abc") (returns 一个 Promise),而是调用 json().

但是等等:如果 bff() returns 一个 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 实际上不是 "true" Promise 但有这三个方便的方法所以你 不必 等待 bff() 如果你只得到它的响应 JSON。但是由于您 do 实际上也想查看响应本身,因此您应该改为执行以下操作:

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
}