跳转到内容

调用服务器端点

端点可以用来提供多种类型的数据。在本节示例中,将展示如何在页面的组件脚本中调用一个服务器端点来显示问候语,而不需要额外的获取请求。

  • 一个开启了 SSRoutput: 'server') 的项目
  1. 在一个新的文件 src/pages/api/hello.ts 中创建一个端点,该端点返回一些数据:

    src/pages/api/hello.ts
    import type { APIRoute } from 'astro'
    export const GET: APIRoute = () => {
    return new Response(
    JSON.stringify({
    greeting: 'Hello',
    }),
    )
    }
  2. 在任何 Astro 页面上,从端点中导入 GET() 方法。使用 Astro 全局对象 来提供请求的上下文,并在页面使用响应数据。

    src/pages/index.astro
    ---
    import { GET } from './api/hello.ts'
    let response = await GET(Astro)
    const data = await response.json()
    ---
    <h1>{data.greeting} world!</h1>