Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string.

My question is whether fetch.js applies gzip compression automatically, or if I need to manually compress and include headers?

return new Promise((resolve, reject) => {
  fetch(api_base + "/api/save-photo", {
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
  })
    .then((response) => {
      if (response.status === 404) {
        throw new Error('404 (Not Found)');
      } else {
        return response.json().then((json) => {
          console.log('save poster response: ', json);
          return json;
        });
      }
    });
});

Answer №1

If you're looking to optimize your code for faster compression, consider using https://github.com/nodeca/pako, which is a quicker port of zlib.

To implement this, start by adding the following import:

import { gzip } from 'pako';

Next, make the necessary change from:

body: JSON.stringify(payload)

To:

body: await gzip(JSON.stringify(payload))

Additionally, include the header:

'Content-Encoding': 'gzip',

For those who prefer not to use the await/async syntax, here's an alternative example:

return new Promise((resolve, reject) => {
  gzip(JSON.stringify(payload)).then((gzippedBody) => {
    fetch(api_base + "/api/save-photo", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Encoding': 'gzip',
        'Content-Type': 'application/json'
      },
      body: gzippedBody
    })
      .then((response) => {
        if (response.status === 404) {
          throw new Error('404 (Not Found)');
        } else {
          return response.json().then((json) => {
            console.log('save poster response: ', json);
            return json;
          });
        }
      });
  });
});

Answer №2

Assuming that the payload in your code snippet is not compressed, I also needed a way to compress it and ensure an asynchronous process for seamless integration with my existing codebase. The challenge I faced was incorporating zlib compression without using callbacks.

To address this issue, I adopted the following approach...

In a utility module, I imported zlib as follows:

import zlib from 'zlib'

I defined two functions as shown below...

async function asyncCompressBody(body) {

    const compressedData = await compressBody(body);
    console.log("Data Compressed");

    return compressedData;

}

function compressBody(body) {

    return new Promise( function( resolve, reject ) {

        zlib.deflate(body, (err, buffer) => {
            if(err){
                console.log("Error Zipping");
                reject(err);
            }

            console.log("Zipped");

            resolve(buffer);
        });
    });

}

The compressBody function wraps zlib.deflate inside a promise, while asyncCompressBody is an async function enabling the use of await in calling functions.

To implement this in the main function, I utilized the following code structure...

let compressedBody = await asyncCompressBody(jsonContent);

let headers = new Headers();
headers.append("Content-Type","application/json");
headers.append("Content-Encoding","zlib");

const response = await fetch(url,
    {method: 'POST',
    headers: headers,
    body: compressedBody});

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 hindering me from fetching the information stored in my json file?

Currently, I am delving into learning AngularJS by working on a simple webpage for a company. This page will showcase products that are fetched from a json file. Following a tutorial from the AngularJS website, which covers the exact task I aim to achieve, ...

Array of Arrays Jolt Transformation Specification

I have a JSON input with specific fields and values. I need help creating the expected output in JSON format. Input JSON: { "Features": [ "fields": [ { "name": "featureName" ...

Issue with grunt-crx task detected

In my Gruntfile, I've integrated the grunt-crx task as shown below: crx: { packExtension: { src: "../build/unpacked", dest: "../build/dist" } } Whenever I execute the crx task on its ow ...

Converting multiple WordPress plugins into a single JSON option

Having a plugin with numerous options, I am utilizing an angular application on the frontend to display them all. In order to store these options in the database as JSON data, I need to ensure that all 10 options are saved within a single row in the wp_opt ...

Angular and Three JS collaboration leads to misplacement of canvas rendering

Currently in the process of developing code for a website, I am attempting to integrate Three JS with Angular. After conducting some research, I have found that this combination is feasible and I have successfully merged these two libraries. However, I am ...

Stop accidental form submissions on iOS devices by disabling the return button

In my Ionic 3 application running on iOS, I encountered a bug that allows users to submit a form even when the submit button is disabled. Despite trying different solutions from this source, I have not been successful in resolving it. To prevent accidenta ...

Transformation of JSON data into a structured dataframe

Investigating club participation by analyzing data retrieved as JSON through a URL request. The JSON obtained and loaded using json_loads is presented below: df = [{"club_id":"1234", "sum_totalparticipation":227, "level&q ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

JS How can I generate individual buttons in a loop that trigger separate actions?

Currently, I am working with loops in jQuery to create a series of boxes that contain specific values. The problem arises when I try to assign actions to each box based on the values from an array. For example, I want each box to trigger a different alert ...

Make the adjustment from an H1 tag to an H2 tag with the help of

I need assistance with changing the HTML code from using an <h1> tag to a <h3> tag, using Vanilla JavaScript. Here is the code snippet in question: <h1 class="price-heading ult-responsive cust-headformat" data-ultimate-target=" ...

Tips on updating a div with jQuery AJAX in my PHP script - help needed!

My jQuery call to PHP is functioning well. However, I am trying to figure out if it's possible to directly output the new content of a specific div from the PHP code using the echo statement. Is this achievable? In the past, I would return the update ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

positioning a text input in the center instead of at the top of the page

Hello everyone, I am just starting out with HTML and I have a question. How can I make the Username: <input type="text" name="Username" style="- margin-top: 200px;"> appear in the center of the page instead of at the top? I've tried changing the ...

Partial view encountering Dropzone JS function error

I am currently using jquery-modal by Kyle Fox and I've run into a problem. Whenever I try to open the modal window, my partial view gets loaded into it. However, I keep seeing this error in the console: Dropzone.options.dropzone is not recognized a ...

The requested resource does not have the 'Access-Control-Allow-Origin' header, resulting in a 401 error

I've been working on integrating spell check functionality using the Bing Spell Check API, but I've run into a 401 error. The specific error message is: The requested resource does not have an 'Access-Control-Allow-Origin' header. This ...

Switch the hue when altered

My document contains various input elements such as text, radio buttons, and checkboxes. I want each of these elements to change color when a change is made. This is the method I am currently using: $("document").on('click', 'change', ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Issue with Proper Display of JSON Unicode Characters in AngularJS

When I receive this JSON array, I am using Angular to display it. Here is a shortened example: $scope.results = [{"description": "\u003ca href=\"http://google.com \" target=\"_blank\"\u003eClick Here\u003c/a&bs ...

Transform Dictionary Containing Lists into CSV Format

Data Source Here is the initial JSON structure: { "foo":[ "asd", "fgh" ], "bar":[ "abc", "xyz", "ert" ], "baz":[ ...

Condense categories

Hello there, I'm currently working on a table that contains different groups, and I am trying to figure out how to collapse categories within my table. Check out the Plunker here This is the HTML code snippet I am using: <table border=1> ...