You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Astro文件服务端访问URL查询参数?

在Astro中获取URL查询参数

针对你的需求,在example.astro里获取{hello: "meow"}有两种常用方式,分场景选择:

1. 服务器端获取(Astro Frontmatter)

如果你的站点是SSR模式,或者需要在页面构建/渲染前获取参数,可以在组件的frontmatter中通过Astro全局对象拿到:

---
// example.astro
// 从请求URL中提取查询参数
const { searchParams } = Astro.request.url;
// 转换成对象形式得到 { hello: "meow" }
const queryParams = Object.fromEntries(searchParams);
---

<!-- 在页面中使用参数 -->
<p>hello参数的值:{queryParams.hello}</p>

2. 客户端浏览器端获取

如果是静态生成(SSG)站点,或者需要在用户交互时动态获取参数,用浏览器原生API实现:

---
// example.astro
---

<!-- 页面内容 -->
<script>
// 从当前页面URL提取查询参数
const urlParams = new URLSearchParams(window.location.search);
// 转换成对象形式
const queryParams = Object.fromEntries(urlParams);
console.log(queryParams); // 控制台输出 { hello: "meow" }
</script>

内容的提问来源于stack exchange,提问作者ThomasReggi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:48:20