How to parse querystring parameter from URL in Fastify server?
Asked Answered
C

3

11

I am a totally new to fastify but I have a fastify server running. I want to parse query string such as:

http://fake.com/?user=123&name=ali

I want to get "user" and "name" values from the URL above. My current code is like this:

fastify.route({
  method: 'GET',
  url: '/',
  handler: async (request, reply) => getCompanyUsers(request, reply, services)
});

I want to get values of "user" and "name" and then pass the values to getCompanyUsers function.

Any help is appreciated.

Thanks

Caerleon answered 31/7, 2019 at 14:27 Comment(0)
R
11

You can access the querystring using request.query

You can look at the official documentation here https://github.com/fastify/fastify/blob/main/docs/Reference/Request.md

Roquelaure answered 31/7, 2019 at 14:32 Comment(0)
L
11
 fastify.route({
  method: 'GET',
  url: '/',
 schema: {
   // request needs to have a querystring with a `name` parameter
   querystring: {
    name: { type: 'string' }
  }
   },
   handler: async (request, reply) => {
   // here you will get request.query if your schema validate
  }
})
Lysippus answered 17/10, 2019 at 7:23 Comment(0)
G
0

Similar to how you get params in fastify, ie: request.params.somepathparam, query is the same:

let user = request.query.user
let name = request.query.name
Governorship answered 20/1 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.