边缘安全加速平台 EO 获取客户端 URL 信息

该示例捕获传入的 HTTP 请求,并返回 HTML 页面,该页面显示了请求 URL 的详细信息,可用于调试和展示请求参数、路径及来源等。

相关产品
边缘安全加速平台 EO 产品页,含版本规格、价格与购买入口。

一、示例代码

// 添加fetch事件监听器,当有请求进入时触发,使用handleRequest函数处理请求,并返回响应addEventListener('fetch', event => { event.respondWith(handleRequest(event.request))})function handleRequest(request) { // 解析请求 URL const url = new URL(request.url) // 提取 URL 各个组成部分 const { href, // 完整 URL protocol, // 协议(如 http:) hostname, // 主机名(如 example.com) port, // 端口(如果有指定) pathname, // 路径(如 /path) search, // 查询字符串(如 ?query=123) hash // 井号后面的片段(如 #section) } = url // 构造 HTML 响应内容 const htmlContent = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Request URL Details</title> </head> <body> <h1>Request URL Details</h1> <p><strong>Complete URL:</strong> <a href="${href}">${href}</a></p> <p><strong>Protocol:</strong> ${protocol}</p> <p><strong>Hostname:</strong> ${hostname}</p> ${port ? `<p><strong>Port:</strong> ${port}</p>` : ''} <p><strong>Pathname:</strong> ${pathname}</p> <p><strong>Search:</strong> ${search}</p> ${hash ? `<p><strong>Hash:</strong> ${hash}</p>` : ''} </body> </html> `; // 返回 HTML 格式的响应 return new Response(htmlContent, { headers: { 'Content-Type': 'text/html;charset=UTF-8' } })}

二、示例预览

在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,即可预览到示例效果。

三、相关参考

·Runtime APIs: Request

·Runtime APIs: Response

赞 (0)
上一篇 4天前
下一篇 4天前