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

如何在Astro的TypeScript API路由中获取clientAddress

在Astro服务端API端点中获取客户端IP的方法

在Astro的API路由(比如pages/api/下的.ts文件)里,不需要调用Astro对象,直接从路由处理函数的上下文参数中解构clientAddress即可,这个值和.astro页面里的Astro.clientAddress完全一致。

修改你的API代码如下:

// pages/api/create-user.ts
export async function post({ request, clientAddress }) {
    console.log(await request.json());

    // 直接使用上下文里的clientAddress
    const IP = clientAddress;

    return {
        body: JSON.stringify({
            name: 'Astro',
            url: 'https://astro.build/',
            ip: `Your IP: ${IP}`
        }),
    };
}

注意事项

如果你的项目部署在反向代理服务器(如Nginx、Vercel、Netlify)之后,需要在astro.config.mjs中开启trustProxy配置,确保Astro能正确识别客户端的真实IP(否则可能拿到代理服务器的IP):

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  server: {
    trustProxy: true,
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:53:20