MSW (Mock Service Worker) 将端口从 8080 更改为

Nor*_*ldt 2 javascript testing intercept jestjs service-worker

request-url 的 MSW 文档说:

// Only "POST https://api.backend.dev/users" requests match this handler
rest.post('https://api.backend.dev/users', responseResolver)
// Given your application runs on "http://localhost:8080",
// this request handler URL gets resolved to "http://localhost:8080/invoices"
rest.get('/invoices', invocesResolver)
Run Code Online (Sandbox Code Playgroud)

进行了很多搜索,但找不到一些有关如何更改端口的文档。所以它可能是这样的http://localhost:3001

ket*_*ito 5

上面强调了“localhost:8080”,因为相对于默认值的相对 URLlocalhost将解析为localhost:8080/url. 您不一定需要对其进行自定义。

相对网址

任何相对 URL 都与当前应用程序的位置相关。因此,如果您的应用程序正在运行http://localhost:3000并且您定义了一个相对/user处理程序,那么您会http://localhost:3000/user自动获得。

// If my app runs on :3000, the handler above intercepts
// a GET http://localhost:3000/user. I don't have to specify
// hostnames/ports for relative URLs against the application address.
rest.get('/user', resolver)
Run Code Online (Sandbox Code Playgroud)

绝对网址

如果您(出于某种原因)需要为外部本地主机服务(不是的应用程序)定义一个处理程序,则可以包含其绝对 URL:

// My app runs on :3000 but I want to intercept and mock a request
// to another app that runs on localhost:3001. Here's how I do it:
rest.get('http://localhost:3001/user', resolver)
Run Code Online (Sandbox Code Playgroud)