Skip to content

Commit

Permalink
fix: router issue with query params (#77) (#78)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
  • Loading branch information
seho-dev and pi0 committed Mar 29, 2022
1 parent 2cf0f4b commit 229964e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,16 @@ export function createRouter (): Router {
// Main handle
router.handler = defineEventHandler((event) => {
// Match route
const matched = _router.lookup(event.req.url || '/')

// Remove query parameters for matching
let path = event.req.url || '/'
const queryUrlIndex = path.lastIndexOf('?')
if (queryUrlIndex > -1) {
path = path.substring(0, queryUrlIndex)
}

const matched = _router.lookup(path)

if (!matched) {
throw createError({
statusCode: 404,
Expand Down
10 changes: 10 additions & 0 deletions test/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ describe('router', () => {
app = createApp({ debug: false })
router = createRouter()
.add('/', () => 'Hello')
.add('/test/?/a', () => '/test/?/a')
.get('/test', () => 'Test (GET)')
.post('/test', () => 'Test (POST)')

Expand All @@ -29,6 +30,15 @@ describe('router', () => {
const res2 = await request.post('/test')
expect(res2.text).toEqual('Test (POST)')
})
it('Handle url with query parameters', async () => {
const res = await request.get('/test?title=test')
expect(res.status).toEqual(200)
})

it('Handle url with query parameters, include "?" in url path', async () => {
const res = await request.get('/test/?/a?title=test')
expect(res.status).toEqual(200)
})

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

0 comments on commit 229964e

Please sign in to comment.