mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.98k stars 519 forks source link

Preserve the original request URL in "onUnhandledRequest" warnings #2125

Closed kettanaito closed 7 months ago

kettanaito commented 7 months ago

Prerequisites

Environment check

Node.js version

v20.11.0

Reproduction repository

Always specify repros. Don't follow my lead.

Reproduction steps

  1. Set up MSW in the browser.
  2. Configure the onUnhandledRequest callback:

    await worker.start({
    onUnhandledRequest(request, print) {
    console.log('URL:', request.url)
    if (/\.(css|js|json|png|jpg|gif)$/.test(request.url)) {
      return
    }
    
    print.warning()
    },
    })
  3. Make a request like /fo/bar/?t=123

Current behavior

MSW prints a clean URL, making it hard to understand why my custom onUnhandledRequest logic is not matching this request:

Screenshot 2024-04-05 at 15 45 08

Expected behavior

MSW preserves the unhandled request URL as-is, which includes keeping its query parameters and fragments.

kettanaito commented 7 months ago

How to fix this

The fix would be right here:

https://github.com/mswjs/msw/blob/e83a6699bc40a4fc2a593a93346158b8b8b61649/src/core/utils/request/onUnhandledRequest.ts#L25

The reason we use toPublicUrl() here is to omit the document's origin and print a relative URL. There are two ways to fix this:

  1. Always print an absolute URL. I.e. remove toPublicUrl and rely on request.url as-is.
  2. Still get a potentially relative URL but copy the search and fragment from the original request.url (we construct a URL instance out of it anyway).
nagadevkrishna commented 7 months ago

Hi, I made a change and raised the PR: https://github.com/mswjs/msw/pull/2128

kettanaito commented 7 months ago

Released: v2.2.14 🎉

This has been released in v2.2.14!

Make sure to always update to the latest version (npm i msw@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.