Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting multiple query params #44

Open
yusukebe opened this issue Apr 10, 2022 · 1 comment
Open

Getting multiple query params #44

yusukebe opened this issue Apr 10, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@yusukebe
Copy link

Hi there ✋

It's not sure that you know this way already, but I want to tell you. I know how to get multiple query params with ittry-router. Inside of the handler, we can get Request object. So, we can get multiple query params by getting url strings, passing into URLSearchParams, and using getAll() method. This is code:

import { Router } from 'itty-router'

const router = Router()

router.get('/', (req) => {
  const url = new URL(req.url)
  const search = new URLSearchParams(url.search)
  const params = search.getAll('foo')
  return new Response(JSON.stringify(params), {
    headers: {
      'Content-Type': 'application/json',
    },
  })
})

addEventListener('fetch', (event) => event.respondWith(router.handle(event.request)))

Run with Wrangler or Miniflare, and then access like this:

$ curl 'http://localhost:8787/?foo=hello&foo=morning&foo=night'
["hello","morning","night"]

You can get multi values.

Note:

You can also use Hono instead of ittry-router.

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  const url = new URL(c.req.url)
  const search = new URLSearchParams(url.search)
  const params = search.getAll('foo')
  return c.json(params)
})

export default app

If it is annoying, feel free to close this issue.

@spencerwooo
Copy link
Owner

Thanks! I just came across Hono today, and seeing its performance advantages over itty-router - I may switch over when I have time ;)

Cheers, and thanks for letting me know.

(I'll keep this open when I eventually refactor the project to use Hono or get multiple queries implemented.)

@spencerwooo spencerwooo added the enhancement New feature or request label Apr 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants