Skip to Content
DocsRequestsQuery Params

Query Params

Reading the ?name=value pairs a client appends to the URL

Overview

Query params are read the same way path params are, using queryParam() instead of pathParam(). Nothing needs to be declared in paths — any client can append any query string to any path, so queryParam() is available on every resource regardless of what its paths look like.

Objectives

To gain familiarity with:

  • reading a query param with queryParam(); and
  • how a repeated param resolves.

Reading a Query Param

import { Resource } from "@drashland/drash/modules/http.polyfill.js"; class Users extends Resource { paths = ["/users"]; // Node hands the chain a context object, so `params` is attached to that // rather than to a Web `Request`, and you write the response instead of // returning one. GET(context) { const page = context.params.queryParam("page"); context.response.end(`page=${page}`); } }

A param the client did not send comes back as undefined rather than throwing, so check the value instead of catching an error.

Repeated Params

A client can send the same name more than once. queryParam() returns the first value:

// GET /users?sort=asc&sort=desc request.params.queryParam("sort"); // "asc"

Verification

With a resource whose paths are ["/users"] running on localhost:1447:

curl "http://localhost:1447/users?page=2" -> page=2 curl "http://localhost:1447/users?x=1&page=2" -> page=2 curl "http://localhost:1447/users" -> page=undefined

Position does not matter — a param reads the same whether it is first in the query string or last.

Last updated on