Getting response headers from an AJAX POST requestWould you like to know how to

I am having trouble retrieving response headers sent by the server. Despite being able to view the response headers in Chrome Dev Tools, when trying to access them using JavaScript, I am only getting an empty object.

(I am utilizing the isomorphic-fetch library for making XHR requests.)

        fetch("http://my.cors.url/postsomedata", {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(myjsobject),
        })
        .then(response => response.headers)
        .then((headers) => {
            console.log(headers); // empty object
        })

This question is distinct from the topic discussed in How to get Response headers in AJAX as I am not utilizing jQuery for this task.

Answer №1

It turned out that the issue lied with my back-end server's CORS configuration. Since I am utilizing spring boot, I needed to set up the application in a specific way to pass custom headers into the xhr response.

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .exposedHeaders("MyHeader");
        }
    };
}

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

Creating a mesmerizing glass effect in Three.js using a PNG image mask on a video texture

The other day, I revisited activetheory.net and was captivated by the beautiful glass effect on the Homescreen logo border. I tried to replicate it by examining the minified code and discovered they were using a PNG as a mask. I successfully loaded a PNG ...

Before starting the operation, the beforeEach() function in the asynchronous Jasmine test is not being called

I'm currently coding a test for my client-server modules. One challenge I'm facing is that I need to ensure the server is running before the client sends its requests. To achieve this, I am attempting to utilize the beforeEach method. However, th ...

While everything ran smoothly on my local machine, the app crashed on Heroku as soon as I integrated express-handlebars into the

After adding this code to the app, it started crashing on Heroku servers. Interestingly, removing these codes resolved the issue and the app worked perfectly on Heroku. However, the app works fine with these codes when tested locally. const exphbs = req ...

What is the method for obtaining an element with a class name that does not match a specific value?

I'm trying to figure out how to select an element with a class name that is different from the value passed in. For example: $(document).ready(function () { $(document).on('change', '#allRolesDD', function () { var toS ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...

Include a new item into the existing one and iterate through the information within it

Is there a way to iterate through the compositions array within the sample object and then use that data to fill the compositions array of the objToAdd object? const sample = { lin: { "clo": [ { "mode": 19, "id": ...

The occurrence of an error is triggered by the Jquery.ajax()

Here's a useful link for you to try out: If you take a closer look, you'll see that it takes the $_GET['fname'] parameter and outputs the content I need. I made an attempt at solving this: $.ajax({ type: 'GET', url: ...

Retrieve the HTML structure from an AJAX response

I'm working on an Ajax call in my code: callAjaxController: function(){ var url = Routing.generate('ajax_price'); $.ajax({ type: "GET", url: url, cache: false, success: funct ...

How can we efficiently determine if any of the keys in an array of objects contains a value that is present in another array of arrays object?

I am working on developing a filtering system that checks for the existence of project technologies in the arrOfObjs.name. If a match is found, then the filter will allow the project to be displayed in the DOM. This filter specifically involves using a com ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

The error message "ng: command not found" popped up despite successfully installing the latest @angular/cli using npm linking

Here is the information about my current setup: Node version: v10.15.3 NPM version: 6.4.1 I attempted to run the following command: Command: npm i -g angular/cli An error occurred while executing: npm ERR! /usr/local/bin/git ls-remote -h -t ssh:// ...

What is the best way to implement a JavaScript pattern matching for both "aaaa" and "aaa aaa"?

Can anyone help me create a pattern that can accept both strings with spaces and without spaces in the same text box? I would appreciate any guidance on how to achieve this. Thanks! ...

Avoiding the refreshing of the footer when navigating through pages

In my music application, there is a simple player located in the footer. Users can choose songs from the main page list and play them in the footer. The current requirement is that even if a user navigates from the home page to other pages (profile, bookma ...

What are the benefits of using Array.prototype.forEach.call(array, cb) instead of array.forEach(cb)?

After revisiting some snapshots from the recent ng-europe conference, I stumbled upon a slide that appears to showcase snippets of code from Angular 2. You can view it here: (Source: ) One thing that confuses me is this: What could be the reason behind t ...

Displaying a dynamic progress bar across all elements in fullscreen mode

I am looking to implement a full-screen indeterminate progress bar that overlays all screen elements. Here is my specific use case: When a user fills out a form, including an email field, the email id is checked against a database via ajax. While waiting ...

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...

AngularJS utilizes JSON objects to store and manipulate data within

My task requires accessing information from an array that is nested inside another array in Json format. Here's a more detailed example: [ { "id": 1, "name": "PowerRanger", "description": "BLUE", "connections": [ {"id": 123,"meg ...

Display the JSON outcome with console.logging

As I delve into the world of APIs, JSON, and JQuery, I've encountered a roadblock. How can I retrieve the following information, "name: The Old Mill Cafe," and log it to the console from my JQuery call? Below is my current code snippet: $(document). ...

Is there another option that I can try since sending an echo before I sleep is not

I'm facing a dilemma on how to proceed. I want to send an echo that AJAX can interpret and respond to. However, the issue arises because the PHP script executes in its entirety before echoing. Despite trying various methods like flushing from SOF, it ...

Refreshing the three.js scene seamlessly within a single-page web application

I am currently working on a single page application that consists of multiple "slides," each implemented as a different hidden div, which becomes visible when it is the current slide. One of these slides features a canvas element and a ThreeJS scene. The ...