分类: 阿里云

  • 使用阿里云ESA边缘函数获取访问用户IP

    
    async function handleRequest(request) {
        const url = new URL(request.url);
        const path = url.pathname;
        const ip = request.headers.get('x-forwarded-for')?.split(',')[0]||request.headers.get('x-alicdn-security-xff')
        if(path==='/'){
            return new Response(ip, {
                headers: {
                "content-type": "text/html;charset=UTF-8",
                },
            })
        } else if(path==='/json'){
            return new Response(JSON.stringify({ ip }), {
            headers: {
                'content-type': 'application/json',
            },
            });
        } else if(path==='/info'){
            const info = {
                ip,
                geo: request.info
            }
            return new Response(JSON.stringify({ info }), {
                headers: {
                    'content-type': 'application/json',
                },
            });
        } else {
            return new Response("404", {status: 404})
        }
        
    }
    
    export default {
      async fetch(request) {
        return handleRequest(request);
      }
    };
    

    获取访问IP(支持IPv6)