I'm unable to access the query parameters of an astro file.
Given the url http://localhost:3000/example?hello=meow
:
How can I access {hello: "meow"}
from within the example.astro
file?
If you're writing an API route, then you'd use a .ts
or .js
file [source].
In that, you can write a get
method like this:
export async function get({request}) {
// process the URL into a more usable format
const url = new URL(request.url)
const params = new URLSearchParams(url.search)
// set up a response object
const data = {
hello: params.get('hello'),
};
// this will yield { hello: 'meow' } on your Astro server console
console.log(data)
// return the response
return new Response(JSON.stringify(data), {
status: 200
}); }
From an .astro
file you can access the url through const { url } = Astro.request;
for SSR, I think. For static pages, you can do it through const url = Astro.url;
[source].