javascript - 如何在 Astro API 路由中存取 clientAddress?
我知道我們可以在 Astro 中使用 Astro.clientAddress 值訪問使用者的 IP 位址,但這只適用於 .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}`
}),
};
}
我想在這個 typescript 文件中直接訪問使用者的 IP 地址,但我認為 Astro 在 .ts 文件的上下文中並沒有提供。那麼該如何實現呢?
我查看了相關文件,但無法找到如何訪問它的方法。
答案#1
你可以在端點函數中的 API 上下文物件中存取 clientAddress。
import type { APIContext } from 'astro';
export function get({ clientAddress }: APIContext) {
return {
body: `Your IP address is: ${clientAddress}`
}
}
