I am new to Deno and I was wondering what the equivalent variable of the PHP variable $_SERVER["REQUEST_URI"]
would be?
I tried countless functions which were returned as "not a function".
I am new to Deno and I was wondering what the equivalent variable of the PHP variable $_SERVER["REQUEST_URI"]
would be?
I tried countless functions which were returned as "not a function".
2
Answers
Deno has a couple of different web server APIs (and then there are frameworks built on top of them). But I think most (all?) of them provide the handler with a
Request
object, which has aurl
property telling you what the requested URL was.PHP can have a global variable storing the request URL because it works in a different way than Deno.
In Deno, you usually get the URL inside of some request handler function in one of its parameters, but you usually don’t even need that if you are using any framework to help you handling those requests (see examples below).
Using the bare
serve
utility from thestd
library, you can handle requests like this:In the above example the
req.url
exists because it was passed to thishandler()
function every time it was invoked (for every request) because this function was registered as a handler for all requests by invokingserve(handler);
If you save it as
main.ts
then you can run this program with:The default port is 8000 so you can run curl to make a request like this:
which will display:
Now, this is quite low level API and in practice you would probably want to use a library like oak. E.g. to have an equivalent server using oak, which works differently than
serve
from thee previous example, you’d use something like this:So here, you access the URL not be
req.url
but withctx.request.url.href
(or starting with something else thanctx
if you named your parameter differently). The.href
is here to get the full URL as a string becausectx.request.url
is an object – an instance of URL).But you usuall don’t access your URL lik that, but instead you define routes with separate handlers that get run for the specific URLs, e.g.:
Note that we don’t have to test the URL inside of those handlers but of course we can. They already know which URL they are serving because the
oak
library runs them for the correct routes that they need to serve.So it all depends on what libraries of framework you are using to handle the requests – which you would usually do for production code instead of using the
serve
directly (unless you have some very specific needs).To find a good framework for for your needs, see: