0

I'm trying to intercept REST API request using MSW, but it keeps hi-jacking static images in public folder

https://mswjs.io/docs/api/is-common-asset-request/

I tried to use isCommonAssetRequest, but it is not working.

I have multiple handler.

import { type HttpHandler } from 'msw'

import boardHandlers from './board.handler'
import contributionHandlers from './contribution.handler'
import { recruitHandlers } from './recruit.handler'
import taskHandlers from './task.handler'

export const handlers: HttpHandler[] = [
  ...boardHandlers,
  ...taskHandlers,
  ...contributionHandlers,
  ...recruitHandlers,
]

import { isCommonAssetRequest } from 'msw'
import { createRoot } from 'react-dom/client'

import './index.css'
import App from './App'

const enableMocking = async () => {
  if (!import.meta.env.DEV) {
    return
  }
  const { worker } = await import('../mocks/browser')
  return worker.start({
    onUnhandledRequest: (request) => {
      if (isCommonAssetRequest(request)) {
        return
      }
    },
  })
}

enableMocking()
  .then(() => {
    createRoot(document.getElementById('root')!).render(<App />)
  })
  .catch((err) => {
    console.error('MSW initialization failed', err)
  })
[MSW] Uncaught exception in the request handler for "GET http://localhost:5173/assets/images/logo.svg":

TypeError: Unexpected CLOSE at 47, expected END
    at mustConsume (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:187:11)
    at parse (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:263:5)
    at stringToRegexp (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:335:25)
    at pathToRegexp (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:396:10)
    at match (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:269:12)
    at matchRequestUrl (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:556:18)
    at HttpHandler.parse (http://localhost:5173/node_modules/.vite/deps/msw.js?v=c62e9274:875:37)
    at HttpHandler.run (
1
  • MSW already applies isCommonAssetRequest unless you use the onUnhandledRequest option, but you could narrow the troubleshooting down by not using a condition and then add a simpler condition like if (request.url.includes('.svg'))). You can also remove your existing handlers to see if any of them accidentally matches with your assets. Finally you can add a handler for your asset and explicitly use passthrough to handle it in msw. Hopefully this should give some more information about the issue. Commented Oct 22 at 8:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.