一、示例代码
// 添加fetch事件监听器,当有请求进入时触发,使用handleRequest函数处理请求,并返回响应addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); }); // 定义一个异步函数handleRequest,用于处理传入的请求 async function handleRequest(request) { // 初始化一个空字符串用于存放HTML内容 let html_content = ""; // 定义HTML的样式 let html_style = "body{padding:6em; font-family: sans-serif;} h1{color:#0000ff;}"; // 获取用户的地理位置信息 html_content += "<p> asn: " + request.eo.geo.asn + "</p>"; // 自治域系统编号 html_content += "<p> countryName: " + request.eo.geo.countryName + "</p>"; // 国家名称 html_content += "<p> countryCodeAlpha2: " + request.eo.geo.countryCodeAlpha2 + "</p>"; // 国家两字母代码 html_content += "<p> countryCodeAlpha3: " + request.eo.geo.countryCodeAlpha3 + "</p>"; // 国家三字母代码 html_content += "<p> countryCodeNumeric: " + request.eo.geo.countryCodeNumeric + "</p>"; // 国家数字代码 html_content += "<p> regionName: " + request.eo.geo.regionName + "</p>"; // 地区名称 html_content += "<p> regionCode: " + request.eo.geo.regionCode + "</p>"; // 地区代码 html_content += "<p> cityName: " + request.eo.geo.cityName + "</p>"; // 城市名称 html_content += "<p> Latitude: " + request.eo.geo.latitude + "</p>"; // 纬度 html_content += "<p> Longitude: " + request.eo.geo.longitude + "</p>"; // 经度 // 构建HTML响应内容 let html = `<!DOCTYPE html> <head> <title> Geolocation: Hello World By Edge Functions.</title> <style> ${html_style} </style> </head> <body> <h1>Geolocation: Hello World By Edge Functions.</h1> <p> Welcome to try out the geolocation feature of Edge Functions.</p> ${html_content} </body>`; // 返回一个新的Response对象,包含HTML内容和相应的headers return new Response(html, { headers: { "content-type": "text/html;charset=UTF-8", // 设置响应的Content-Type头部,指定返回内容为HTML }, }); }
二、示例预览
在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,即可预览到示例效果。
三、相关参考
·Runtime APIs: addEventListener
·Runtime APIs: Request
·Runtime APIs: Response