Skip to content

Commit 229964e

Browse files
seho-devpi0
andauthored
fix: router issue with query params (#77) (#78)
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
1 parent 2cf0f4b commit 229964e

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/router.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,16 @@ export function createRouter (): Router {
4242
// Main handle
4343
router.handler = defineEventHandler((event) => {
4444
// Match route
45-
const matched = _router.lookup(event.req.url || '/')
45+
46+
// Remove query parameters for matching
47+
let path = event.req.url || '/'
48+
const queryUrlIndex = path.lastIndexOf('?')
49+
if (queryUrlIndex > -1) {
50+
path = path.substring(0, queryUrlIndex)
51+
}
52+
53+
const matched = _router.lookup(path)
54+
4655
if (!matched) {
4756
throw createError({
4857
statusCode: 404,

test/router.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ describe('router', () => {
1111
app = createApp({ debug: false })
1212
router = createRouter()
1313
.add('/', () => 'Hello')
14+
.add('/test/?/a', () => '/test/?/a')
1415
.get('/test', () => 'Test (GET)')
1516
.post('/test', () => 'Test (POST)')
1617

@@ -29,6 +30,15 @@ describe('router', () => {
2930
const res2 = await request.post('/test')
3031
expect(res2.text).toEqual('Test (POST)')
3132
})
33+
it('Handle url with query parameters', async () => {
34+
const res = await request.get('/test?title=test')
35+
expect(res.status).toEqual(200)
36+
})
37+
38+
it('Handle url with query parameters, include "?" in url path', async () => {
39+
const res = await request.get('/test/?/a?title=test')
40+
expect(res.status).toEqual(200)
41+
})
3242

3343
it('Not matching route', async () => {
3444
const res = await request.get('/404')

0 commit comments

Comments
 (0)