Get Cloudflare's HTTP_CF_IPCOUNTRY header with javascript?

后端 未结 4 1083
再見小時候
再見小時候 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:52

    @Quentin's answer stands correct and holds true for any javascript client trying to access server header's.

    However, since this question is specific to Cloudlfare and specific to getting the 2 letter country ISO normally in the HTTP_CF_IPCOUNTRY header, I believe I have a work-around that best befits the question asked.

    Below is a code excerpt that I use on my frontend Ember App, sitting behind Cloudflare... and varnish... and 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');
    

    The performance is really really great, don't be afraid to call this function even before you call other APIs or functions. I have found it to be as quick or sometimes even quicker than retrieving static resources from Cloudflare's cache. You can run a profile on Pingdom to confirm this.

提交回复
热议问题