Intercepting requests and extracting body data gives you full control over the network traffic, allowing you to verify, mock, or manipulate requests in your tests.

page.spec.ts
import { test } from "@playwright/test";

test("intercept requests and extract body data", async ({ page }) => {
  // Intercept request and log the method and URL
  page.on("request", async (request) => {
    console.log(">>", request.method(), request.url());

    if (request.method() === "POST") {
      const requestBody = await request.postDataJSON(); // Capture POST request body
      console.log("Request Body:", requestBody); // Log the body content
    }
  });

  // Intercept response and log status and URL
  page.on("response", (response) => {
    console.log("<<", response.status(), response.url());
  });

  // Navigate to the page that triggers requests
  await page.goto("https://example.com/");
});

Why It’s Useful:

  • Capture POST Data: Easily extract and inspect the body of POST requests, which is often key for testing user input or API interactions.
  • Ensure Correct Data: Make sure the data being sent (e.g., form submissions, login credentials) matches expectations.
  • Debugging: Helps identify issues by allowing you to inspect both the request and response, ensuring that the right data flows through the system.
Verified Agency by DesignRush badge
Top Clutch Companies Romania 2022 badge
Tip NodeJS Developers Timisoara 2023 badge
Top IT Services Companies Education Romania 2023 badge
Top Software Developer Timisoara 2023 badge