【问题标题】:How can I access the url query parameters from an Astro file (server side)?如何从 Astro 文件(服务器端)访问 url 查询参数?
【发布时间】:2022-09-26 02:29:07
【问题描述】:

我无法访问 astro 文件的查询参数。

给定网址http://localhost:3000/example?hello=meow

如何从example.astro 文件中访问{hello: \"meow\"}

  • 这回答了你的问题了吗? How to get the querystring parameters with Astro
  • @BadPiggie 不,这是专门使用客户端/前端 js 上的查询参数。
  • server side 是什么意思。 Astro 中的页面是预先呈现的并且完全是静态的
  • @BadPiggie 有一个 output: \"server\" 模式,它代替了 ssr。

标签: javascript astrojs


【解决方案1】:

如果您正在编写 API 路由,那么您将使用 .ts.js 文件 [source]
在那里,您可以像这样编写get 方法:

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
  }); }

我认为,从.astro 文件中,您可以通过const { url } = Astro.request; 访问 SSR 的 url。对于静态页面,可以通过const url = Astro.url; [source]进行。

【讨论】:

  • 嘿,哈桑,我刚试过这个,它确实与这里的 output: "server" 配置一起工作:stackblitz.com/edit/…
  • 您能否在答案中添加有关将output: "server" 添加到配置中的说明?
  • 我按照官方文档中的说明进行了您需要的集成[SSR Docs]。我使用了Vercel integration,我所要做的就是输入export default defineConfig({output: 'server', adapter: vercel()});。你有什么想法?
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
相关资源
最近更新 更多