调整暂存帮助部分结构 & 简化获取当前用户IP代码
This commit is contained in:
@@ -3,30 +3,15 @@
|
||||
import {headers} from 'next/headers'
|
||||
|
||||
export async function getClientIp(): Promise<{ip?: string, error?: string}> {
|
||||
const header = await headers()
|
||||
try {
|
||||
// 1. 从headers获取
|
||||
const headersList = await headers()
|
||||
|
||||
// 尝试常见header
|
||||
const forwardedFor = headersList.get('x-forwarded-for')
|
||||
const forwardedFor = header.get('x-forwarded-for')
|
||||
if (forwardedFor) {
|
||||
const ip = forwardedFor.split(',')[0].trim()
|
||||
if (ip) return {ip}
|
||||
}
|
||||
|
||||
const realIp = headersList.get('x-real-ip')
|
||||
const realIp = header.get('x-real-ip')
|
||||
if (realIp) return {ip: realIp}
|
||||
|
||||
// 回退到ipify
|
||||
const response = await fetch('https://api.ipify.org?format=json', {
|
||||
cache: 'no-store',
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
return {ip: data.ip}
|
||||
}
|
||||
|
||||
return {error: '无法获取IP'}
|
||||
}
|
||||
catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user