Skip to content

Getting multiple query params #44

@yusukebe

Description

@yusukebe

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions