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

