mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
523 stars 118 forks source link

ERR_MODULE_NOT_FOUND Cannot find module #587

Closed tommaso-bissoli closed 5 days ago

tommaso-bissoli commented 1 week ago

Hi,

first of all: I'm quite ignorant on Node JS. I do not kwno if I'm doing right.

MY GOAL I want to intercept a fetch inside my React app before it can do anything. I searched and found Node Request Interceptor could be the solution.

This is the filsystem structure:

src/   middleware/

Inside I created intercept.js with this simple code:

import { RequestInterceptor } from 'node-request-interceptor'
import withDefaultInterceptors from 'node-request-interceptor/presets/default'

const interceptor = new RequestInterceptor(withDefaultInterceptors)

interceptor.use( req => {
  console.log(req)
})

Inside package.json I have this script:

  {
    "scripts": {
       "intercept": "node src/middleware/intercept",
    }
  }

In the terminal when I run npm run intercept I get this error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Sites_LAB\react-widget\react-widget-parcel\node_modules\node-request-interceptor\presets\default' imported from C:\Sites_LAB\react-widget\react-widget-parcel\src\middleware\intercept.js at finalizeResolution (node:internal/modules/esm/resolve:265:11) at moduleResolve (node:internal/modules/esm/resolve:933:10) at defaultResolve (node:internal/modules/esm/resolve:1157:11) at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:383:12) at ModuleLoader.resolve (node:internal/modules/esm/loader:352:25) at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:227:38) at ModuleWrap. (node:internal/modules/esm/module_job:87:39) at link (node:internal/modules/esm/module_job:86:36) { code: 'ERR_MODULE_NOT_FOUND', url: 'file:///C:/Sites/_LAB/react-widget/react-widget-parcel/node_modules/node-request-interceptor/presets/default' }

All the urls to the node module in the error log are correct aside the fact that the real file system structure is this:

node_modules/   node-request-interceptor/     bin/

with inside of bin folder: presets/ or interceptors/.

The "bin/" part is missing in the import but even adding it the error still logs.

What I'm doing wrong? What I'm missing?

Thank you.

kettanaito commented 5 days ago

Hi, @tommaso-bissoli.

It looks like you've found this library through the window in the past. It used to be called node-request-interceptor but that package is a few years old now.

You have two options:

  1. Use @mswjs/interceptors instead (this library).
  2. Use msw directly, which is more developer-friendly, especially if you are not deeply familiar with Node.js.

This library, Interceptors, is primarily designed as a low-level solutions for developers to build their own API mocking libraries. I highly recommend you use https://mswjs.io/ instead.