The cachedResponse does not contain any header information

I'm currently working on figuring out the age of a cached response by utilizing the date header of the response. I attempted to do this using a plugin that utilizes cachedResponseWillBeUsed. However, when trying to access cachedResponse.headers, I am not getting any data. Is this supposed to happen? Code provided below:

const cachedResponsePlugin = {
  cachedResponseWillBeUsed: ({ cachedResponse }) => {
    let headers = new Headers(cachedResponse.headers);
    console.log(cachedResponse.headers); // Empty
    headers.set("X-Cached-Response", "true");

    return cachedResponse.arrayBuffer().then((buffer) => {
      return new Response(buffer, {
        status: cachedResponse.status,
        statusText: cachedResponse.statusText,
        headers,
      });
    });
  },
};

Answer №1

When it comes to addressing your query, there are a couple of key points to consider:

Recording Headers in the console

console.log(cachedResponse.headers)
typically does not provide useful output in most browsers. (For instance, Chrome may just display Headers {}.)

The Headers object is iterable, but console.log() does not automatically iterate over its values. To view the values, you should explicitly iterate during logging. One simple method is using ... for iteration and enclosing the result in [] to gather the values into an array.

To implement this approach, try

console.log([...cachedResponse.headers])
to access the desired values.

Interpreting the headers

In general, response headers remain intact when saved in the Cache Storage API.

However, with cross-origin responses, only specific headers will be accessible when retrieving that response from cache. (In cases where Workbox manages the cachedResponse parameter retrieval, it handles cache reading automatically.)

For further insights on this matter and recommendations regarding the usage of the Access-Control-Expose-Headers response header for cross-origin responses, refer to this informative blog post.

If you're working with same-origin responses, adjusting this header may not be required. It's plausible that the availability of the header was overlooked due to the aforementioned logging issue.

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

Prevent angular from being executed through a JavaScript function triggered by a button click

Here is a button: <button ng-click="deleteCompany(company.id)" class="btn btn-danger" onClick="return window.confirm('This will permanently delete the entity\n Are you sure you want to delete this post?'); "> <s ...

Using the import statement to bring in module one from "./two" is causing a malfunction in my JavaScript file while working with Laravel 5.4 broadcasting using Pusher

Node Version 8.6.0 npm version 5.3.0 Chrome Issue (Version 61.0.3163.100) Error: Unexpected token import Mozila Problem (Version 56.0 (64-bit)) SyntaxError: Only top-level import declarations are allowed import one from "./two"; ...

The callback function does not get invoked when using JSONP

Learning jsonP has been a challenge for me as I am relatively new to it. I have done my research by reading various articles but when trying out a simple example, the callback function fails to execute. Surprisingly, there are no errors or exceptions logge ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

Sequencing asynchronous functions in Angular: Ensuring one function runs before another

When working with a save function that requires you to call another function to retrieve the revision number and make an API call, both of which are asynchronous in nature, how can you ensure one function waits for the other to execute? $scope.getRevision ...

Running the command "npm start" will keep your application running indefinitely

Even when the status shows online, I am still unable to run the port on 8014. Whenever I try using pm2 to start tools/srcServer.js "scripts": { "prestart": "babel-node tools/startMessage.js", "start": "npm-run-all --parallel test:watch open:src", "ope ...

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

Utilize the identical mathematical equation across various jQuery values

I have a JavaScript code that calculates the size of circles on the screen based on multiple variables. Currently, I am repeating the same equation for each circle by numbering all the variables accordingly. Is there a way to simplify this process and run ...

Make the minimum height of one div equal to the height of another div

My query is somewhat similar to this discussion: Implementing a dynamic min-height on a div using JavaScript but with a slight twist. I am working on a dropdown menu within a WordPress site, integrated with RoyalSlider. The height of the slider div adjust ...

CKEditor directive in AngularJS does not properly enforce the maxlength attribute in textarea

I am currently working on an AngularJS application with the CKEditor plugin. I have created a directive for CKEditor and everything seems to be functioning properly. However, I am facing an issue where I need to limit the character length to 50. I tried us ...

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

Having trouble importing JS into HTML file with NodeJS

I have created a web server using NodeJS that serves the file index.html. However, when I attempt to add a JavaScript file to my HTML document, the browser displays an error message stating The resource "http://localhost:3000/includes/main.js" was blocked ...

Trouble using the Javascript Notification API on Google Chrome for Android when attempting to call it directly from a webpage

I've been working with the JavaScript Notification API to display small messages to my users. This feature works perfectly on all desktop browsers I've tested, including Chrome, but for some reason it doesn't work on Chrome for Android (spec ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

The functionality of AngularJS's state URL depends on numerical URLs for navigation

Currently, I am utilizing the following URL in my state setup: .state('forum.spesific', { url: '/:articleId', templateUrl: 'modules/forum/client/views/forum.client.view.html', controller: 'forumCont ...

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Importing textures and loading mtl files in Three.js from various web addresses

Something strange is happening with my Roblox API integration. I'm trying to retrieve the OBJ file, MTL file, and Texture file using the API. The main API link I have is https://t2.rbxcdn.com/ef63c826300347dde39b499e56bc874b, which leads me to two cru ...

When using angular $resource.save for savings, the view is forced to redraw and reflow because of the collection watcher

One of the challenges I'm facing involves loading and storing a model using $resource in AngularJS. This particular model is an aggregate with nested collections, which are displayed in an HTML view using ng-repeat. The structure of the model looks l ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...