Request Parameters
Learning objectives
- You know how to use request parameters with Hono.
In Hono, request parameters can be accessed through the req
attribute of the context. The req
attribute has a method query
, which takes the name of the parameter as an argument and returns the value of the parameter. If the parameter is not present, the method returns undefined
.
With Vanilla Deno, we implemented an application that responds to requests with a name that was passed as a request parameter. The code for that application is shown below.
const handleRequest = (request) => {
const url = new URL(request.url);
const params = url.searchParams;
return new Response(`Name: ${params.get("name")}`);
};
Deno.serve(handleRequest);
With Hono, the same would be achieved as follows:
import { Hono } from "https://deno.land/x/hono@v3.12.11/mod.ts";
const app = new Hono();
app.get("/", (c) => c.text(`Name: ${c.req.query("name")}`));
Deno.serve(app.fetch);
Running the above program and querying it, we see the following:
curl localhost:8000
Name: undefined%
curl localhost:8000?name=Harry
Name: Harry%
Checking whether a specific request parameter exists can be done with a simple if
statement. The c.req.query("key")
call returns undefined
if there is no value for a given key. The following shows an example of how to check for the existence of a request parameter and use it if it exists.
import { Hono } from "https://deno.land/x/hono@v3.12.11/mod.ts";
const app = new Hono();
app.get("/", (c) => {
let name = "Jane";
if (c.req.query("name")) {
name = c.req.query("name");
}
return c.text(`Hi ${name}`)
});
Deno.serve(app.fetch);
Modern JavaScript features a ??
operator that can be used to simplify the above code. The ??
operator returns the value of the right-hand side if the left-hand side is null
or undefined
. The following shows how to use the ??
operator to simplify the above code.
import { Hono } from "https://deno.land/x/hono@v3.12.11/mod.ts";
const app = new Hono();
app.get("/", (c) => {
let name = c.req.query("name") ?? "Jane";
return c.text(`Hi ${name}`)
});
Deno.serve(app.fetch);