Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source:

var request = require('request');
var requestOptions = {
    url: 'http://whatever.com/getDataWithCompression',
    gzip: true  // <--- only this is necessary
};
request(
    requestOptions,
    function (error, response, data) {
        // manipulate data (already decompressed)
    }
);

However, I have some JavaScript code embedded within an HTML document that also needs to perform an HTTP request. In this case, without the node.js request module, I am resorting to using XMLHttpRequest:

var request = new XMLHttpRequest();
request.open('GET', 'http://whatever.com/getData', true);
request.onload = function() {
    // perform operations on request.responseText
};
request.send();

Despite extensive searching online, I am struggling to figure out how to make an HTTP request with XMLHttpRequest and handle gzipped data compression. Any assistance would be greatly appreciated.

Answer №1

Resolution

After extensive research and experimentation, I have successfully determined the method to accomplish this task. Assuming that you have successfully integrated the pako JavaScript library for decompression purposes (refer to this link for JavaScript Links), by including it in your code as follows:

<script type="text/javascript" src="pako.js"></script>

You can proceed with decompressing data, particularly when dealing with a compressed JSON format, using the following script:

var data;
var request = new XMLHttpRequest();
request.responseType = 'arraybuffer';
request.onload = function() {
  data = JSON.parse(pako.inflate(request.response, { to: 'string' }));
};
request.open('GET',"data.gzip");
request.send();

It is worth mentioning that the use of JSON.parse is essential due to the fact that the inflated response is stored as a string, and any saved data resembling {"chocolate":["dark","white",...]} will contain backslashes, such as {\"chocolate\": ...}. Hence, employing the parse function helps in accurately parsing the string to obtain a JSON object.

Error Rectification:

Anomalies may arise during the interpretation of data by your XMLHttpRequest. Initially, I attempted setting the request type as "arraybuffer," then utilizing a FileReader to process the response string. However, it was later realized that converting an array buffer to a blob, only to convert it back to an array buffer within the FileReader, proved to be redundant and confusing.

Answer №2

There may be an issue specific to the browser being used: . This issue has been known to occur on certain versions of Internet Explorer. To resolve this, you will need to manually extract the response using a library like the one found here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to remove text messages from a channel that only allows images?

I have developed a Discord bot named YES with a specific text channel for images only. My goal is to program the bot to automatically delete any text messages in this channel and respond with "You cannot send text messages." However, I also want to create ...

What is the best way to showcase Vue data of a selected element from a v-for loop in a

Here is an example of how my json data is structured. I have multiple elements being displayed in a v-for loop, and when one is clicked, I want to show specific information from that element in a modal. [{ "id": 1, "companyNa ...

Node Express Caching: What are the best strategies for managing view access?

When using Express, you can take advantage of its built-in cache mechanism by setting up with app.enable('view cache'). However, the challenge lies in distinguishing between views that should be cached and views that should always be served fresh ...

JavaScript, detecting repeated characters

I need to create a script that checks an input box (password) for the occurrence of the same character appearing twice. This script should work alongside existing regex validation. I believe I will need to use a loop to check if any character appears twice ...

The message sent by the postman returns an empty JSON response

When attempting to send a request to test the MongoDB connection, I am getting an empty object as a response. I have checked and suspect that my test.http file is being treated as text instead of JSON... despite using app.use(express.json()) for parsing. T ...

Experiencing peculiar behavior with the delete keyword in JavaScript

Okay, so here's the deal... var obj = people[0]; obj.oAuthID = null; delete obj.oAuthID; This code snippet returns... { "uuid": "39b2b45f-1dde-4c9a-8765-1bc76f55848f", "oAuthID": null, "date": "2013-10-21T16:48:47.079Z", "updated": "2013-10 ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Unable to convert the BSON type to a Date in MongoDB

I am currently facing an issue while attempting to filter data stored in MongoDB utilizing parameters from the URL. Whenever I send the request, the server crashes and displays the error message: can't convert from BSON type string to Date I attemp ...

Email replay feature

Having an issue with my email validation function. I found the code I'm using here: Repeat email in HTML Form not the same. Why? The problem I am facing is that if you incorrectly enter your email in the first input "eMail" and correctly in the seco ...

Is a VS required for npm installation of serialport?

When attempting to install serialport for my electron project, I consistently encounter an error after running npm install serialport: E:\Windows\Desktop\Work\Electron\testing>npm install serialport (Various error messages rel ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

Utilizing the $set method to capture a jQuery variable and append it to a Vue array object

Currently, I am retrieving data from an API using jQuery's getJson method to extract the information. After successfully obtaining the data, my aim is to assign it to a Vue array object by making use of app.$set. Although I have managed to extract an ...

AngularJS - ng-repeat not updating when property array changes

I have a loop in my HTML using ng-repeat: <div class="row"> <div ng-repeat="item in model.painel track by item.codigoIncidente"> <strong>{{item.restante.horaMinutoSegundo}}</strong> </div> </div> In ...

Ways to execute postinstall script in package.json exclusively on macOS operating system

On my MacOS machine, I need to run the postinstall script to address a temporary issue in react-native-maps: "scripts": { "postinstall": "sed -i '' '/Google.*\\.[h|m]/d' node_modules/react-native-maps/lib/ios/AirMaps.xcodep ...

Leverage variables in Ajax to retrieve the data of an HTML element

Seeking assistance in converting multiple lines into a single for loop. var optie1 = ""; if($('#form #optie1_check').is(':checked')) { optie1 = $('#form #optie1_naam').val(); } var optie2 = ""; if($('#form #optie2_ch ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Disable the ability to click on the indicators in the Bootstrap carousel

Seeking assistance with customizing tweeters bootstrap Carousel functionality. I have removed the controls and now want to switch slides according to my own logic while displaying slide indicators. How can this be achieved? Preferably seeking a solution ...