代码之家  ›  专栏  ›  技术社区  ›  Visrut

如何在Astro-api路由中访问clientAddress?

  •  0
  • Visrut  · 技术社区  · 3 年前

    我知道我们可以访问用户的 IP Astro中的地址使用 Astro.clientAddress 值,但这只适用于 .astro 页面。

    // your-ip.astro
    
    ---
    const detectedIp = Astro.clientAddress;
    ---
    
    <h1>
    Your IP: {{ detectedIP }}
    </h1>
    

    但在我的情况下,我在Astro中创建了一个服务器端API端点,如下所示。

    // pages/api/create-user.ts
    
    export async function post({ request }) {
        console.log(await request.json());
    
    
        // I want to do like this in typescript endpoint file
        // const IP = Astro.clientAddress;
    
    
        return {
            body: JSON.stringify({
                name: 'Astro',
                url: 'https://astro.build/',
                ip: `Your IP: {IP}`
            }),
        };
    }
    

    我想访问用户的 IP 此中的地址 typescript 文件本身,但我认为 Astro 中未提供 .ts 文件上下文。那么如何实现呢?

    我查看了它周围的文档,但找不到如何访问它。

    1 回复  |  直到 3 年前
        1
  •  1
  •   The Otterlord    3 年前

    您可以访问 clientAddress 从端点函数中的API上下文对象。

    import type { APIContext } from 'astro';
    
    export function get({ clientAddress }: APIContext) {
      return {
        body: `Your IP address is: ${clientAddress}`
      }
    }