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

Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements a ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 ...

An error callback is triggered when the HttpClient delete function encounters an issue, despite receiving a successful

My attempt to remove a basic student object using its ID is functioning correctly. However, instead of displaying the success message, it appears as an error message. Java backend code -> Controller code: @DeleteMapping("/student/{$id}") ...

Using MongoDB and NodeJS to retrieve data from a promise

When I make a request to the database using promises, my goal is to extract the values of "latitude" and "longitude" for all documents and store them in an array. This is how I am currently approaching it: const promises = [ dbo.collection("users").f ...

Experiencing difficulties loading webpages while attempting to execute Routes sample code using NodeJS

As a beginner in Javascript, I am attempting to execute the example code provided in the documentation for routes. The code snippet is as follows: var Router = require('routes'); var router = new Router(); router.addRoute('/admin/*?&apos ...

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

Utilizing React JS and lodash's get method within a single function

Is it possible to display two string objects in the same line using Lodash get? Can I achieve this by chaining (_.chain(vehicle).get('test').get('test2))? Below is a snippet of the JSON file: { "results": [ { " ...

Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). A ...

Trouble with X-editable linking to database for updates

Utilizing the X-Editable plugin within my PHP application to update fields in a table and utilizing a POST file to update the database. Below is the form code: <table id="restaurant" class="table table-bordered table-striped"> <tbody> ...

The screen suddenly turns black just moments after starting the video

Currently, I am utilizing the Youtube JavaScript API to embed videos on my webpage and control a playlist. However, I keep encountering an error where the video turns black right after loading the title, play icon, and loading icon. Initially, it seems lik ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

I'm having trouble getting jquery css to function properly in my situation

I am trying to implement a fallback for the use of calc() in my CSS using jQuery CSS: width: calc(100% - 90px); However, when I tried running the code below, it seems like the second css() function is not executing. I suspect that there might be an issu ...

Is it achievable for a modal popup to automatically move to a specified location?

I need assistance with... Is it feasible to display an external webpage within a modal window and have that page automatically scroll to a specific section (such as an anchor point)? ...

Looking to retrieve just your Twitter follower count using JavaScript and the Twitter API V1.1?

I am trying to retrieve my Twitter follower count using JavaScript/jQuery in the script.js file and then passing that value to the index.html file for display on a local HTML web page. I will not be hosting these files online. I have spent weeks searching ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Sending Information within Controllers with AngularJS

I have a unique scenario in my application where I need to pass input from one view to another. I have set up a service as shown below: .service('greeting', function Greeting() { var greeting = this; greeting.message = 'Default&ap ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

An issue has been identified with the functionality of an Ajax request within a partial view that is loaded through another Ajax request specifically in

Here is the current scenario within my ASP.NET MVC application: The parent page consists of 3 tabs, and the following javascript code has been implemented to handle the click events for each tab: Each function triggers a controller action (specified in t ...

Leverage AJAX data to dynamically generate an input field within a Laravel application

. Hey everyone, I'm currently working on implementing ajax for a search functionality. The goal is to display links to the search results' pages along with checkboxes next to each result, allowing users to select orders for printing. Although I ...