繁体   English   中英

Cloudflare Workers:未定义请求

[英]Cloudflare Workers: request is not defined

我正在尝试使用 Cloudflare Workers 根据用户所在的国家/地区(使用 Cloudflare 的request.cf.country )在下拉列表中自动选择一个值。

这是我写的代码:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let html_content = ""
  html_content += "<p> Detected Country: " + request.cf.country + "</p>"

  let html = `${html_content}
  
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
    document.getElementById('edit-field-country').value = request.cf.country;
</script>
`

  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },})
}

这部分运行良好,可以正确输出国家代码:

<p> Detected Country: " + request.cf.country + "</p>

不幸的是,自动选择不起作用,因为这里有一个问题:

document.getElementById('edit-field-country').value = request.cf.country;

我究竟做错了什么?

我应该早点定义request.cf.country吗?

request.cf.country未在您尝试访问它的上下文(浏览器)中定义。

尝试改变这个:

 let html = `${html_content}
  
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
    document.getElementById('edit-field-country').value = request.cf.country;
</script>
`

改为:

 let html = `${html_content}
  
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
    document.getElementById('edit-field-country').value = '${request.cf.country}';
</script>
`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM