Deno nuggets: Use headers and query params like a plain object
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
The headers & query params interfaces exposes has, get, set, entries, etc. APIs to work with the KV pairs. It may be easier to access the data simply using obj.key rather than obj.get(‘key’).
How to use headers like a plain object?
headers.someHdr;
headers['another-hdr'];
How to use query params like a plain object?
const qp=new URL(someUrl).searchParams;
qp.someQp;
qp['another-qp'];
Solution
We can create a new object that convert headers/query params into plain object using JS core’s Object.fromEntries() API.
Imports
No imports are required.
Create plain object
The JS core’s Object.fromEntries() API along with headers/query params’s entries() API to create a plain JS object. The converted object can then be used to access keys through regular dot notation.
const headers = Object.fromEntries(req.headers.entries());
const queryParams = Object.fromEntries(
new URL(req.url).searchParams.entries(),
);
The plain objects can be accessed normally:
$ curl "http://localhost:8100?a=b&c-d=e" -H ":some-hdr: some-val"//--headers; //{accept: "*/*", host: "localhost:8100", "some-hdr": "some-val", "user-agent": "curl/7.77.0"}
headers.host; //localhost:8100
headers['some-hdr']; //some-val
queryParams; //{ a: "b", "c-d": "e" }
queryParams.a; //b
queryParams['c-d']; //e
The following is the code of an HTTP server that echoes the headers and query params in the response object:
import { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
const headers = Object.fromEntries(req.headers.entries());
const queryParams = Object.fromEntries(
new URL(req.url).searchParams.entries(),
);
return new Response(JSON.stringify({
headers,
queryParams,
}));
}serve(reqHandler, { port: 8100 });
Here is a test using curl:
$ curl "http://localhost:8100?a=b&c-d=e" -H 'some-hdr: some-val'
{"headers":{"accept":"*/*","host":"localhost:8100","some-hdr":"some-val","user-agent":"curl/7.77.0"},"queryParams":{"a":"b","c-d":"e"}}