Skip to main content

How to get the HTTP request headers from the initial page request in ReactJS

So, the easier solution is to simply make an AJAX request to the server on page load. As you are using ReactJS, make the request on componentDidMount

componentDidMount() {

        var req = new XMLHttpRequest();
        req.open('GET', document.location, false);
        req.send(null);
        var headers = req.getAllResponseHeaders().toLowerCase();
        headers = headers.split(/\n|\r|\r\n/g).reduce(function (a, b) {
            if (b.length) {
                var [key, value] = b.split(': ');
                a[key] = value;
            }
            return a;
        }, {});
        console.log(headers);
    }

Comments