Home > Software engineering >  How to get both response JSON and headers with Got?
How to get both response JSON and headers with Got?

Time:10-27

I'm using enter image description here

CodePudding user response:

This works because of the value you're awaiting. The conventional example:

const body = await got.get("...").json();

is equivalent to:

const res = got.get("...");
const body = await res.json();
          // ^ note

but not:

const res = await got.get("...");
         // ^ note
const body = res.json();

From the Promise API docs:

The main Got function returns a Promise.

Although in order to support cancelation, PCancelable is used instead of pure Promise.

The json method is attached to this PCancelable object, not the value it resolves to. If you try to call it on the response, therefore, you get TypeError: res.json is not a function.

What you want is something like:

const res = await got.get("...");
const body = JSON.parse(res.body);
const headers = res.headers;
// ...

That said, if you're doing this for pagination reasons you could also look into their API for that.

  • Related