Extract the date from the HTTP response headers when making a POST request with Fetch API

UPDATED

I need help extracting the Date from my response headers in a POST request. Currently, I'm only able to retrieve the Content-Type header. Is there a way to access the date information as well?

After making a POST request, these are the response headers:

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

Below is the utility function I am using for sending the POST request:

export default async function postData(url, func, audience, requestObj) {
    const accessToken = await func({
        audience: audience,
    });

    const myHeaders = new Headers();

    myHeaders.append('authorization', `Bearer ${accessToken}`);
    myHeaders.append('Content-Type', 'application/json');

    const raw = JSON.stringify(requestObj);

    const requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow',
    };

    const response = await fetch(url, requestOptions);
    const transactionDate = response.headers.get('Date');

    //This returns null
    console.log('Date', transactionDate);

    //This returns only the Content-Type
    for (let pair of response.headers.entries()) {
        console.log(pair[0] + ': ' + pair[1]);
    }
    if (!response.ok) {
        if (response.status >= 500 && response.status <= 599) {
            throw new Error(
                'A server error occurred and we were unable to submit your data.'
            );
        } else if (response.status >= 400 && response.status <= 499) {
            const text = await response.text();
            throw new Error(text);
        } else {
            throw new Error(`${response.status}: ${response.statusText}`);
        }
    }

    const result = await response.json();
    return result;
}

Answer №1

This marks the conclusion of submitData:

const output = await reply.json();
return output;

Instead of returning the response directly, this function decodes the JSON-formatted response and returns the resulting data structure.

The retrieved data structure does not encompass the headers, which are stored within the reply object.

If you require access to this information beyond the scope of submitData, you must retrieve the value (reply.headers) and include it in your return (perhaps as part of an array or object that also contains the data from output).

Answer №2

It has been brought to light in the comments that the Date found in the response header is considered a Forbidden Header Name, as documented here: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name. Therefore, it cannot be accessed.

If you need to access the Date, you can utilize Access-Control-Expose-Headers as described here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers. Alternatively, if there are concerns with using this method, consider returning a custom HTTP header containing the date information instead.

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

When you click the "Select All" button in a JavaScript dialogue box, all of the checkboxes on the main page will automatically be selected

After clicking a button on the main page to add a SKU, a new window opens with a search field, as shown in the image below. In this pop-up window, there is a "Check All" button that, when clicked, selects all checkboxes on both the pop-up window and the ma ...

I aim to display a well-optimized mobile view by utilizing Bootstrap CSS

I need my website to be mobile responsive and I want the mobile view to have specific changes. Simply adding cd-xs-12 or even cd-sm-12 is not achieving the desired outcome. https://i.sstatic.net/0GU2h.jpg This is the current code I have: ...

Using DataTable with backend processing

Has anyone successfully implemented pagination in DataTable to dynamically generate the lengthMenu (Showing 1 to 10 of 57 entries) and only load data when the next page is clicked? I'm currently facing this challenge and would appreciate some guidance ...

Replacing an item from an object within an array using JavaScript

After researching extensively on this topic and trying various solutions from SO, I am still unable to achieve the desired outcome. I have developed a shopping basket program where users can add items and make purchases by clicking the 'Buy now' ...

Modify the Bootstrap navbar color as you scroll through the page

While utilizing Bootstrap for a theme, I came across this interesting site: . The effect on the navbar caught my attention - it changes color when scrolling down and also modifies the color of elements. Appreciate any insights or advice. Thanks! ...

Effortlessly stream a series of video files in consecutive order using HTML's <video> tag

Having experimented with various approaches: I attempted to utilize hidden video tags and toggle their visibility, but encountered flickering issues. Another strategy involved modifying the src attribute of the video. However, I found that I needed to ...

The functionality of an Ajax call is limited to a single use, regardless of using

For the past couple of weeks, I've been struggling to get my Ajax call to function more than once. As a self-taught individual, I've been trying my best to troubleshoot this issue on my own, but it's really getting to me. Some others facing ...

Angular creating numerous ng-loops

I am encountering an issue in my angular application (angular 1.4.9) where multiple ng-repeats are being generated unexpectedly. This problem occurs when I implement the following code: HTML: <div class="form-group col-md-3"> <input ng-model=" ...

how to name a collection variable in MongoDB shell using JavaScript

When using the mongo shell with JavaScript, is it possible to dynamically set the collection name in order to work with multiple collections? db.collection.insert() ...

Submitting data to MongoDB on a Click event of a Submit Button

I recently created a newsletter form using React (Image 1). Image1 After clicking submit, the data is sent to MongoDB. For example, each entry made in the input box results in a new entry in MongoDB. Please see the code snippet below: FRONTED FORM PART ...

Is there a way to iterate through this?

I have data that I need to loop over in JavaScript. Since it is not an array, the map function is not working. Can someone help me loop over it or convert it into an array so that I can iterate through it? { "7/15/2021": { "date": ...

The JavaScript code fails to run after implementing highway.js unless the page is manually refreshed

Recently I started using highway.js to implement a fade out/fade in effect while navigating between pages. Despite going through the documentation, I couldn't figure out why my other JavaScript files aren't activating when the new content block l ...

Is there a jQuery tool that can effortlessly add items to a list element?

I'm currently developing a task management application on the web. I have a textarea where users can input tasks, and when they press enter, it should automatically be added to a list element (li). The adding functionality works, but only after refres ...

Struggling with AJAX requests in a cordova/ratchet app for mobile devices

I encountered some challenges when trying to make an AJAX request in my cordova project. $.ajax({ url: "https://mydevserver/REST.php?method=mobileGetData", success: function(result){ alert("successful ajax"); }, error: function(xhr ...

Tips for optimizing nested object array searches

Is there a widely recognized technique to chain .map or .filter or .find functions in order to achieve this type of search? Imagine an array of objects nested within another array of objects customerGroups : [ { id: 1, customers: [{ id ...

Error: When refreshing the webpage, a TypeError occurs because the property '1' is attempting to be read from an undefined object

Retrieving the user collection from firebase: const [userInfo, setUserInfo] = useState([]) useEffect(() => { if (currentUser) { const unsubscribe = db .collection("users") .doc(uid) .onSna ...

Substitute the ajax reply with the text currently displayed

I am facing an issue with the AJAX response in my HTML page. Currently, the response is being appended on top of the existing text instead of replacing it. Here is a snippet of my code: <html> <head> <h2>This is a test</h2> ...

The while-loop using Regex adds only a single value to my array

Within my variable htmlContent, there lies a string filled with properly formatted HTML code, which includes various img tags. The goal is to extract each value from the src attribute of these images and place them all in an array named srcList. The issu ...

Adjust the text appearance of the graph in ApexCharts

Is there a way to adjust the font size of the donut chart generated by using apexchart? You can view the image here. <template> <section> <v-card raised> <v-card-title class="blue--text">Requests Overview</v-card-ti ...

not capable of outputting findings in a sequential manner

I am encountering an issue where my result is not printing line by line, instead everything shows up on a single line. How can I resolve this problem? Here is the code snippet I have tried: <script> function know(){ var num = Number(doc ...