有很多关于如何使用 javascript 获取 http 标头的问题,但由于某种原因,它们没有显示 HTTP_CF_IPCOUNTRY 标头。
如果我尝试使用 php
echo $_SERVER["HTTP_CF_IPCOUNTRY"];
,它可以工作,所以 CF 工作得很好。
可以用javascript获取这个标头吗?
@Quentin 的答案是正确的,并且对于任何尝试访问服务器标头的 javascript 客户端都适用。
但是,由于这个问题特定于 Cloudlfare,并且特定于在 HTTP_CF_IPCOUNTRY 标头中正常获取 2 个字母的国家/地区 ISO,因此我相信我有一个最适合所问问题的解决方法。
下面是我在前端 Ember App 上使用的代码摘录,位于 Cloudflare...和 varnish...以及 fastboot...
function parseTrace(url){
let trace = [];
$.ajax(url,
{
success: function(response){
let lines = response.split('\n');
let keyValue;
lines.forEach(function(line){
keyValue = line.split('=');
trace[keyValue[0]] = decodeURIComponent(keyValue[1] || '');
if(keyValue[0] === 'loc' && trace['loc'] !== 'XX'){
alert(trace['loc']);
}
if(keyValue[0] === 'ip'){
alert(trace['ip']);
}
});
return trace;
},
error: function(){
return trace;
}
}
);
};
let cfTrace = parseTrace('/cdn-cgi/trace');
性能真的非常好,即使在调用其他 API 或函数之前也不要害怕调用这个函数。我发现它比从 Cloudflare 缓存中检索静态资源一样快,有时甚至更快。您可以在 Pingdom 上运行配置文件来确认这一点。
async function getCloudflareJSON(){
let data = await fetch('https://1.1.1.1/cdn-cgi/trace').then(res=>res.text())
let arr = data.trim().split('\n').map(e=>e.split('='))
return Object.fromEntries(arr)
}
getCloudflareJSON().then(cloudflareJSON => console.log(cloudflareJSON.loc))
假设您正在谈论客户端 JavaScript:不,这是不可能的。
数据甚至永远不会靠近浏览器。
要让 JavaScript 访问它,您需要使用服务器端代码读取它,然后将其放入浏览器的响应中。
是的,您必须访问服务器 - 但它不一定是您的服务器。
我有一个购物车,其中几乎所有内容都由 Cloudflare 缓存 - 所以我觉得去我的服务器只获取国家/地区代码是愚蠢的。
相反,我在 Cloudflare 上使用网络工作者(额外收费):
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
var countryCode = request.headers.get('CF-IPCountry');
return new Response(
JSON.stringify({ countryCode }),
{ headers: {
"Content-Type": "application/json"
}});
}
您可以将此脚本映射到诸如
/api/countrycode
之类的路由,然后当您的客户端发出 HTTP 请求时,它基本上会立即返回(对我来说大约是 10 毫秒)。
/api/countrycode
{
"countryCode": "US"
}
一些额外的事情:
自从我写这篇文章以来,他们在
Request.cf
上曝光了更多房产 - 即使是价格较低的计划:
https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
您现在可以获得
city
、region
甚至 longitude
和 latitude
,而无需使用地理查找数据库。
我采用了 Don Omondi 的答案,并将其转换为 Promise 函数以方便使用。
function get_country_code() {
return new Promise((resolve, reject) => {
var trace = [];
jQuery.ajax('/cdn-cgi/trace', {
success: function(response) {
var lines = response.split('\n');
var keyValue;
for (var index = 0; index < lines.length; index++) {
const line = lines[index];
keyValue = line.split('=');
trace[keyValue[0]] = decodeURIComponent(keyValue[1] || '');
if (keyValue[0] === 'loc' && trace['loc'] !== 'XX') {
return resolve(trace['loc']);
}
}
},
error: function() {
return reject(trace);
}
});
});
}
使用示例
get_country_code().then((country_code) => {
// do something with the variable country_code
}).catch((err) => {
// caught the error, now do something with it
});