Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions packages/vite/src/node/__tests__/base.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, expect, test, vi } from 'vitest'
import { baseMiddleware } from '../server/middlewares/base'

function run(url: string, base: string) {
const middleware = baseMiddleware(base, false)
const req: any = { url, headers: {} }
const res: any = {
writeHead: vi.fn().mockReturnThis(),
end: vi.fn(),
}
const next = vi.fn()
middleware(req, res, next)
return { req, res, next }
}

describe('baseMiddleware', () => {
test('strips base from matching requests', () => {
Comment thread
btea marked this conversation as resolved.
Resolved
const { req, next } = run('/foo/bar.js', '/foo')
expect(next).toHaveBeenCalled()
expect(req.url).toBe('/bar.js')
})

test('serves a request to the base itself as root', () => {
const { req, next } = run('/foo', '/foo')
expect(next).toHaveBeenCalled()
expect(req.url).toBe('/')
})

test('does not match paths that only share a partial segment', () => {
const { res, next } = run('/foobar/a.js', '/foo')
expect(next).not.toHaveBeenCalled()
expect(res.writeHead).toHaveBeenCalledWith(404, expect.anything())
})

test('does not match requests outside of base', () => {
const { res, next } = run('/bar.js', '/foo')
expect(next).not.toHaveBeenCalled()
expect(res.writeHead).toHaveBeenCalledWith(404, expect.anything())
})
})
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function baseMiddleware(
const pathname = cleanUrl(url)
const base = rawBase

if (pathname.startsWith(base)) {
if (pathname === base || pathname.startsWith(withTrailingSlash(base))) {
// rewrite url to remove base. this ensures that other middleware does
// not need to consider base being prepended or not
req.url = stripBase(url, base)
Expand Down
Loading