API 接口概览
EdgeOne API 提供了丰富的接口服务,涵盖图片、地理位置、通知等多个领域。所有接口都无需认证,可直接调用。
📋 基本信息
- 基础 URL:
https://160621.xyz/api - API 版本: v1
- 协议: HTTPS
- 数据格式: JSON, 图片二进制
- 跨域: 完全支持 CORS
🚀 快速导航
| 服务分类 | 接口路径 | 功能描述 | 响应类型 |
|---|---|---|---|
| 📍 地理位置 | /geo | 获取访客地理位置信息 | JSON |
| 🖼️ 图片服务 | /img | 根据名称获取人物图片 | JSON |
/img/random | 获取随机适配图片 | 图片 | |
/img/bing | 获取 Bing 每日壁纸 | 图片 | |
| 🔗 链接服务 | /link | 从 KV 存储获取链接数据 | JSON |
| 📢 通知服务 | /notify | 消息推送服务 | JSON |
| 📊 访问统计 | /stats | 获取访问统计数据 | JSON |
🌐 通用参数
所有接口都支持以下通用功能:
请求头
http
User-Agent: [自动识别]
Accept: */*
Origin: [自动处理 CORS]响应头
http
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type🛡️ 错误处理
HTTP 状态码
| 状态码 | 说明 | 处理建议 |
|---|---|---|
200 | 请求成功 | 正常处理响应数据 |
400 | 参数错误 | 检查请求参数格式 |
404 | 资源不存在 | 确认接口路径正确 |
500 | 服务器错误 | 稍后重试或联系管理员 |
错误响应格式
json
{
"error": "错误描述",
"code": "ERROR_CODE",
"timestamp": "2025-01-19T12:00:00Z"
}📱 设备适配
部分接口(如随机图片)会自动适配设备类型:
- 移动端检测: 通过 User-Agent 自动识别
- 图片尺寸: 根据设备返回合适的图片尺寸
- 屏幕方向: 支持横屏/竖屏适配
🔄 缓存策略
建议的客户端缓存策略:
| 接口类型 | 缓存时间 | 说明 |
|---|---|---|
| 地理位置信息 | 1小时 | IP 地址通常不会频繁变化 |
| 随机图片 | 不缓存 | 每次都应获取新的随机图片 |
| 人物图片 | 24小时 | 图片内容相对稳定 |
| Bing 壁纸 | 1天 | 每日更新,可缓存一天 |
| 链接数据 | 1小时 | 根据业务需求调整 |
🚀 使用示例
JavaScript 基础用法
javascript
// 封装基础请求函数
class EdgeOneAPI {
constructor(baseUrl = 'https://www.160621.xyz/api') {
this.baseUrl = baseUrl
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`
try {
const response = await fetch(url, {
headers: {
'Accept': 'application/json,*/*',
...options.headers
},
...options
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
const contentType = response.headers.get('content-type')
if (contentType?.includes('application/json')) {
return await response.json()
} else {
return await response.blob()
}
} catch (error) {
console.error(`请求失败 ${endpoint}:`, error)
throw error
}
}
// 地理位置服务
async getGeoInfo() {
return this.request('/geo')
}
// 随机图片
async getRandomImage(proxy = false) {
const endpoint = proxy ? '/img/random?proxy=true' : '/img/random'
return this.request(endpoint)
}
// 人物图片
async getCharacterImages(name, options = {}) {
const params = new URLSearchParams()
params.append('name', name)
if (options.all) params.append('all', 'true')
if (options.count) params.append('count', options.count.toString())
return this.request(`/img?${params.toString()}`)
}
// Bing 壁纸
async getBingWallpaper() {
return this.request('/img/bing')
}
// 链接数据
async getLinks() {
return this.request('/link')
}
}
// 使用示例
const api = new EdgeOneAPI()
// 获取地理位置
api.getGeoInfo().then(location => {
console.log('访问者位置:', location)
})
// 获取随机图片
api.getRandomImage().then(blob => {
const imageUrl = URL.createObjectURL(blob)
document.body.style.backgroundImage = `url(${imageUrl})`
})React Hook 封装
jsx
import { useState, useEffect, useCallback } from 'react'
const API_BASE_URL = 'https://www.160621.xyz/api'
// 地理位置 Hook
export function useGeoInfo() {
const [location, setLocation] = useState(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const fetchLocation = useCallback(async () => {
setLoading(true)
setError(null)
try {
const response = await fetch(`${API_BASE_URL}/geo`)
const data = await response.json()
setLocation(data)
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchLocation()
}, [fetchLocation])
return { location, loading, error, refetch: fetchLocation }
}
// 随机图片 Hook
export function useRandomImage() {
const [imageUrl, setImageUrl] = useState(null)
const [loading, setLoading] = useState(false)
const fetchRandomImage = useCallback(async () => {
setLoading(true)
try {
const response = await fetch(`${API_BASE_URL}/img/random`)
const blob = await response.blob()
const url = URL.createObjectURL(blob)
// 清理之前的 URL
if (imageUrl) {
URL.revokeObjectURL(imageUrl)
}
setImageUrl(url)
} catch (error) {
console.error('获取随机图片失败:', error)
} finally {
setLoading(false)
}
}, [imageUrl])
useEffect(() => {
fetchRandomImage()
}, [fetchRandomImage])
return { imageUrl, loading, refresh: fetchRandomImage }
}📊 性能优化建议
1. 图片加载优化
javascript
// 懒加载图片
const imageObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
imageObserver.unobserve(img)
}
})
})
// 使用示例
document.querySelectorAll('img[data-src]').forEach(img => {
imageObserver.observe(img)
})2. 请求防抖
javascript
// 防抖函数
function debounce(func, delay) {
let timeoutId
return function (...args) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => func.apply(this, args), delay)
}
}
// 防抖的地理位置请求
const debouncedGetGeoInfo = debounce(async () => {
const location = await api.getGeoInfo()
console.log('地理位置信息:', location)
}, 1000)3. 请求重试机制
javascript
async function retryRequest(requestFn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await requestFn()
} catch (error) {
if (i === maxRetries - 1) throw error
// 指数退避
const delay = Math.pow(2, i) * 1000
await new Promise(resolve => setTimeout(resolve, delay))
}
}
}🎯 开始使用: 选择你需要的服务接口,查看详细的文档说明: