简体   繁体   中英

How to get the querystring parameters with Astro

I'm using quite a new technology called Astro ( https://astro.build/ ) to build a completely static, server side rendered page, shipping zero JS.

I have a page with a form that is a simple text input, when the user fills this in and clicks the submit button, it sends a GET request to an astro page. The url will look something like this....

/?search=1234

What I want to be able to do is get access to that querystring parameter in order to redirect my user to another static page /1234.

I am trying to access the quesrystring parameter with Astro.request, but the object, including the parameters attribute is completely empty.

Is there anyway to access the querystring parameters from a.astro page/file?

I wanted to do the same thing, but this seems to be a bug in Astro that doesn't provide queryString parameters, but here is a way to implement it with just Vanilla javascript, but note that this can be only done client side as it is just javascript...

For the queryString:

localhost:3000/test?search=123

To get the parameters:

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

This approach can be seen in: this question as well

I reached out to the developers of Astro and eventually had an email back. This functionality is not possible with Astro, it is not a bug, rather a misunderstanding from me about how Astro works. The pages in Astro are rendered up-front and are entirely static.

This is possible with Astro and can be done using <script></script> tags in a .astro component.

Here's an example.astro file:

---
<!-- imports go in here -->
---
<script>
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
console.log('params', params);
</script>

<!-- rest of your template markup -->

Documentation of using <script></script> tags in this way with Astro can be found here: https://docs.astro.build/en/core-concepts/component-hydration/

(Scroll down to 'Can I Hydrate Astro Components?').

This feature is specifically there for simple DOM interactivity or cases where you need access to the JavaScript window or document .

you can use Astro.url (available since v1.0.0-rc).

eg

---
const search = Astro.url.searchParams.get('search')! || '';
---

{search ? <p>you searched for: {search}</p>}

<!-- rest of your template markup -->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM