Retrieving data in batches using HTTP in JavaScript

My RESTful service has the capability to batch requests, which I am attempting to do using the Fetch API:

let req1 = {
        url: "/cups/count",
        options: {
           method: 'GET',
           headers: {
               'Content-Type': 'application/http'
           }
       }
    },

    req2 = {
        url: "/spoons/count",
        options: {
           method: 'GET',
           headers: {
               'Content-Type': 'application/http'
           }
        }
    },
    authToken = "Bearer my_token123",
    batchUrl = "http://something.com/batch",
    options = {
        method: 'POST',
        headers: {
            'Authorization': authToken,
            'Content-Type': 'multipart/mixed'
        },
        body: {req1, req2}
    };

    return fetch(batchUrl, options)
        .then(response => response.json())
        .then(items => dispatch(batchSuccess(items)))
        .catch((err) => {
            console.log(err)
        });

However, I keep getting a bad request error. I suspect I may be combining HTTP requests incorrectly.

Is there a simpler approach to achieve this task?

Where in the Network tab of Chrome Dev Tools can I view nested HTTP requests?

Answer №1

The issue with your code stems from not adhering to the correct multipart/mixed request format:

  1. The lack of boundary information in the Content-Type header.
  2. Child requests being sent as plain text within the req1 & req2 objects, without division by boundaries.

To send a valid multipart/mixed request, consider using the node.js module batchelor. This module is known for its simplicity and ease of use.

If you need to send a multipart/mixed request from a browser, you can compile batchelor using build tools like gulp or webpack into "batchelor-compiled.js", which can then be imported into your HTML file.

In terms of developer tools, while Chrome may not offer visibility into child requests, Firefox's debug window's "Params" tab does provide insight on them.

https://i.sstatic.net/sb9ry.png

Answer №2

Check out this batch request example using the Fetch API along with the Gmail Batch REST API.

This code snippet demonstrates fetching content from multiple messages simultaneously.

const response = await fetch("https://www.googleapis.com/batch/gmail/v1", {
  headers: {
    "Content-Type": "multipart/mixed; boundary=batch_boundary",
    Authorization: "Bearer <access_token>",
  },
  method: "POST",
  body: `--batch_boundary
Content-Type: application/http
Content-ID: 1

GET /gmail/v1/users/me/messages/{message-id-1}

--batch_boundary
Content-Type: application/http
Content-ID: 2

GET /gmail/v1/users/me/messages/{message-id-2}

--batch_boundary--`,
});

console.log(await response.text());

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 advantage of using event.target over directly referencing the element in eventListeners?

Suppose there are several buttons in an HTML file and the following code is executed: const buttons = document.querySelectorAll('button'); buttons.forEach((btn) => { btn.addEventListener('click', (e) => { console.log(btn.te ...

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...

Basic HTML code that displays either one or two columns based on the width of the screen

My monitoring website displays dynamic rrd graphs in png format with fixed dimensions. I am looking to adjust the layout based on browser window size - showing the graphs in 1 column if the width is below a certain threshold, and in 2 columns if it exceed ...

Searching through an array to isolate only image files

I am working with an array that contains various file types, all stored under the property array.contentType. I am trying to filter out just the images using array.contentType.images, I believe. Check out the code snippet below: const renderSlides = a ...

I am attempting to change a "+" symbol to a "-" symbol using a Bootstrap toggle feature

Click on the text to reveal more information that drops down below. I am using Bootstrap icons and attempting to show a "+" icon when the toggle is collapsed, and a "-" icon when it's open. I've been trying to use display properties, but haven&ap ...

Revamp the style of the date field in a Material UI dialog

I'm currently working on a React project where I am using Material-UI's date picker component to display date items. However, I find that the default style does not meet my requirements. I would like to use a selector for displaying dates in the ...

Is the camera.lookAt() method still available in the THREE.js library?

While searching for information on setting up the camera, I came across references to the lookAt function in various posts. However, when I checked the THREE.js documentation, I couldn't locate this method. Can anyone help me understand where it went ...

Navigate the cursor beyond the span within the content that is editable

I am currently developing a tag input system for a template builder. My main focus right now is on assisting the editor in distinguishing between regular text and formatted text. I am structuring it similar to WordPress shortcodes, where a templated elemen ...

My Vue.js accordion menu component is experiencing issues with toggle flags, causing it to malfunction

I have been working on my test case using Vue and I recently created a component called MultiAccordion. My intention was to open each slide based on the value of the status[index] flag. However, I am encountering an issue as this component does not seem ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel </pre> Input: import React, { useState } from "react"; import ...

Unable to retrieve the string contained within an element - JavaScript object literal

I am currently facing an issue where I am attempting to retrieve the text content of two div elements with classes .class-date and .class-time, but I keep encountering an Uncaught TypeError stating "e.siblings is not a function". I believe this may be a ...

Implement the heightmap onto the SphereGeometry using three.js

[UPDATE: Refer to this jsfiddle for a live demo along with the relevant code] I am using three.js to create visualizations of celestial bodies with distinct characteristics. While there are no specific examples available on implementing spherical heightm ...

What are the methods for determining if a Triangle intersects a Box3?

Is there a built-in function in THREE.js to determine if a THREE.Triangle overlaps with a THREE.Box3 object? If not, what approach can be taken to achieve this? ...

Database entry does not appear in Internet Explorer until the browser is completely shut down and reopened

Currently, I have a form with two dropdowns. Selecting an option from the first dropdown automatically populates the second dropdown. Everything works well except for a minor issue I observed recently. When I add a new item to the second dropdown, it gets ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

unable to save the information to mongoDB

I've been attempting for the past 3 hours to save data from an HTML form to MongoDB using Node.js. When I click submit, it redirects to another page displaying the submitted data in JSON format, but it's not getting stored in the database. Here ...

Utilizing JQuery Definitions for File Upload in Typescript

I'm currently working with TypeScript and facing an issue with a file upload form. However, when I try to access the files from the input element in my TypeScript code, an error is generated. $('body').on('change', '#upload_b ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

The library 'material-ui' does not have a 'withStyles' export available

Here is the content of my package.json file. Everything was working fine until recently when I started encountering this error. "@material-ui/icons": "1.0.0-beta.42", "chartist": "0.10.1", "classnames": "2.2.5", "material-ui": "1.0.0-beta.41", "npm-ru ...