kwhitley / itty-router

A little router.
MIT License
1.75k stars 78 forks source link

Getting Request headers #57

Closed sidvenu closed 2 years ago

sidvenu commented 3 years ago

I think I am probably gonna sound so stupid to not figure this out on my own - is there a way to get request headers in this? The TypeScript declaration for Request doesn't have a headers property.

Tarnadas commented 3 years ago

I think the TypeScript declarations are wrong here. You can use req.headers.get('Content-Type') e.g.

It also took me some time to figure this out.

kwhitley commented 2 years ago

Hey! Yeah, this follows the standard Request API, but for the sake of compatibility, the TS interface is only a lightweight version of that… rather than strictly requiring Request.

I don’t bother with typing myself, so the type definitions have either been generously cared for by the community or (far worse), occasionally stomped through by myself… usually making more of a mess than it’s worth.

If you think you can help fix the declaration file, by my guest! Just be prepared to explain your changes to me like I’m 3 (not even 5).

😁

benycodes commented 2 years ago

To fix this I declared this type

import { Request as IRequest } from 'itty-router'
export type IttyRequest = IRequest & Request

Then on the router I use as follows:

router.get("*", (request: IttyRequest) => new Response(`You are from ${request.cf?.country}!`))

Which outputs as expected: You are from GB!

@kwhitley