Repository navigation
Mock login handler hard-codes localhost without a port #135
Description
Description
The MSW login handler is defined with the absolute URL http://localhost/api/auth/login. This only matches requests made to HTTP localhost on the default port, while the Vite development server runs on port 3001 by default.
As a result, the login mock does not work with the repository's default pnpm mocked setup.
Steps to reproduce
-
Enter the Web directory:
cd web -
Start mocked mode using the default configuration:
pnpm mocked
-
Open
http://localhost:3001. -
Enter any non-empty username and password and submit the login form.
-
Inspect the browser console and network requests.
Actual behavior
MSW reports an intercepted request without a matching handler:
[MSW] Warning: intercepted a request without a matching request handler:
POST /api/auth/login
The request continues to the Vite server and normally returns:
POST http://localhost:3001/api/auth/login 404 Not Found
The same problem occurs when the development page is opened through 127.0.0.1, a LAN address, a custom hostname or port, or HTTPS.
Expected behavior
The same-origin login request should be intercepted by MSW regardless of the hostname, scheme, or port used to access the development server, and should return the mocked token response.
Cause
The handler uses an origin-specific absolute URL:
NanoKVM-Pro/web/src/mocks/browser.ts
Lines 4 to 13 in da60f0c
| export const handlers = [ | |
| http.post('http://localhost/api/auth/login', () => { | |
| return HttpResponse.json({ | |
| code: 0, | |
| data: { | |
| token: 'mocked_token' | |
| } | |
| }); | |
| }) | |
| ]; |
The application sends the login request using the relative path /api/auth/login:
NanoKVM-Pro/web/src/api/auth.ts
Lines 3 to 8 in da60f0c
| export function login(username: string, password: string) { | |
| const data = { | |
| username, | |
| password | |
| }; | |
| return http.post('/api/auth/login', data); |
The repository's Vite configuration uses port 3001:
NanoKVM-Pro/web/vite.config.ts
Lines 5 to 9 in da60f0c
| export default defineConfig({ | |
| plugins: [react(), viteTsconfigPaths()], | |
| server: { | |
| port: 3001 | |
| }, |
Suggested direction
Use the same-origin relative handler path:
http.post('/api/auth/login', () => {
// mocked response
});NanoKVM already uses this form and can be used as a reference:
A wildcard handler should not be necessary while the frontend API requests are same-origin, and could unintentionally intercept requests intended for another API origin.
Acceptance criteria
- Login is handled by MSW when using the default
http://localhost:3001URL. - Login is also handled through
127.0.0.1and a custom development host or port. - The login request does not fall through to the Vite server or a real backend.
- The mocked response returns
mocked_tokenand allows the mocked login flow to continue.
Activity
[-]Mock 登录接口写死为不带端口的 localhost[/-][+]Mock login handler hard-codes localhost without a port[/+]