I am trying to log the response body from an api call that is initiated by a button click in playwright. I have been at this for a while, with no results. I can log the response status, request headers and response headers, But not the response. Although, running a headed browser I can see the JSON response in Network tab inspect window.
await Promise.all([
page.waitForResponse(resp => resp.url().includes('https://example.com/user-check') &&
resp.status() === 200 && resp.request().method() === 'POST')
.then(async resp => {
console.log("Response URL:", resp.url()); // this works and logs the URL of the response
console.log("Response status:", resp.status()); // this works and logs 200
console.log("Response body:", resp.body()); // this fails
}),
page.click('#clickButton'),
]);
I tried resp.body(), resp.json(), resp.text() all failed with the same error below.
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
response.json: Protocol error (Network.getResponseBody): No resource with given identifier found
I hope someone out there can help.
UPDATE: Based on the response headers, the content is gzip encoded. Therefore, I incorporated the solution provided by ggorlen as below.
const responsePromise = page.waitForResponse(resp =>
resp.url().includes("https://example.com/user-check") &&
resp.status() === 200 &&
resp.request().method() === "POST"
);
await page.click("#buttonClick");
const resp = await responsePromise;
console.log("Response URL:", resp.url());
console.log("Response status:", resp.status());
console.log("Response body:", zlib.gunzipSync(resp.body()));
I am guessing there is a specific way to decode the response body in playwright, because I got this error:
Response status: 200
TypeError [ERR_INVALID_ARG_TYPE]: The "buffer" argument must be of type string or an instance of Buffer, TypedArray, DataView, or ArrayBuffer. Received an instance of Promise