Get Cloudflare's HTTP_CF_IPCOUNTRY header with javascript?

后端 未结 4 1076
再見小時候
再見小時候 2021-02-08 11:08

There are many SO questions how to get http headers with javascript, but for some reason they don\'t show up HTTP_CF_IPCOUNTRY header.

If I try to do with php echo

4条回答
  •  暖寄归人
    2021-02-08 11:26

    I've taken Don Omondi's answer, and converted it to a promise function for ease of use.

    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);
                }
            });
    
        });
    }
    

    usage example

    get_country_code().then((country_code) => {
        // do something with the variable country_code
    }).catch((err) => {
        // caught the error, now do something with it
    });
    

提交回复
热议问题