如何在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
相关产品推荐
相关产品推荐

