一些获取访客的方法需要前后端交互,但是利用 Cloudflare Workers,通过获取 Cloudflare HTTP headers 也可以获取到访客 IP
Cloudflare 提供了对应的文档:Cloudflare HTTP headers · Cloudflare Fundamentals docs
Cloudflare Workers 代码为:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
const request = event.request;
// 如果是预检请求(OPTIONS),则直接返回 CORS 头部
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*', // 允许所有来源
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400', // 缓存 24 小时
},
});
}
// 获取客户端IP
const ip = request.headers.get('CF-Connecting-IP');
const logs = request.headers.get('Cf-Ray');
// 创建 JSON 响应
const data = {
ip: ip,
logs: logs,
};
const response = new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*', // 允许所有来源
},
});
return response;
}
是的,我们可以直接在 Workers 中处理跨域,这里我们构造了一个 json 数组来返回数据
之后在前端中进行调用
// 获取用户端IP
fetch('workers 地址')
.then(response => response.json()) // 解析 JSON 响应
.then(data => {
// 显示 IP 地址
document.getElementById('ip-container').textContent = 'IP 地址: ' + data.ip;
// 显示 logs
document.getElementById('logs-container').textContent = '日志: ' + data.logs;
})
.catch(error => {
console.error('Error fetching data:', error);
document.getElementById('ip-container').textContent = 'Failed to fetch data.';
});
此处评论已关闭