I am experiencing difficulty in retrieving the content-disposition from the client

I am attempting to retrieve a .xlsx file that is generated on the backend using Spring Boot. I am able to retrieve headers on the frontend, which include the content-disposition as shown below. However, I am unable to access the content disposition in the header.

As seen in the image below, Content disposition is not present in the headers; it is found in XHR response headers. Xhr response https://i.sstatic.net/aTL7V.png console.log https://i.sstatic.net/YcPZ3.png

I have enabled CORS policy on the backend,

public class WebSecurityConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

and attempted to get content-disposition on the client side

 public static downloadFile(data: any, untilDestroyed$: DestroyService, toasterService?: ToastrService) {
    const openInWindow = data.body.type === 'application/pdf';
    console.log(data);

    const dispositionHeader = data.headers.get('Content-Disposition'); // There lies the issue - value cannot be retrieved
    const blob = new Blob([data.body], {type: data.body.type});
    const url = window.URL.createObjectURL(blob);

Answer №1

If you're facing issues with accessing header information in Angular4 GET response, this ticket might be helpful: Unable to view 'Content-Disposition' headers in Angular4 GET response

    To address this problem, try implementing the following code snippet:
  
    CorsFilter corsFilter = new CorsFilter();
    corsFilter.setAllowedHeaders("Content-Type, Access-Control-Allow-Headers, Access-Control-Expose-Headers, Content-Disposition, 
    Authorization, X-Requested-With");
    corsFilter.setExposedHeaders("Content-Disposition");

Answer №2

The response header known as "Access-Control-Expose-Headers" serves to guide a server in specifying which headers can be accessed by scripts running within a browser, especially when processing cross-origin requests.

To enable custom headers to be utilized in browser scripts, the server (such as a spring boot backend) must explicitly define these headers.

This can be achieved either through CorsFilter or by specific declaration as shown below:

HttpHeaders headers = new HttpHeaders();
List<String> allowedHeaders = new ArrayList<>();
allowedHeaders.add("Content-Disposition");
headers.setAccessControlExposeHeaders(allowedHeaders);

Learn more about Access-Control-Expose-Headers on MDN

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

Dependencies in Angular 2 are essential for efficient functioning

Let's examine the dependencies listed in package.json: "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", "@angular/core": "2.2.1", "@angular/forms": "2. ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

Convert Angular 2 Observable to a regular value

Currently using version 6.3 of NGX Data Table, I am facing an issue where I cannot bind to an observable collection. How can I convert an Angular Observable Collection into a standard non-observable Array? Below is the code snippet for the service: priva ...

The state is accurate despite receiving null as the return value

I'm feeling a bit lost here. I have a main component that is subscribing to and fetching data (I'm using the redux dev tools to monitor it and it's updating the state as needed). In component A, I am doing: public FDC$ = this.store.pipe(sel ...

Retrieve the injectable value when importing SubModule into the App Module

Let me provide some background information... I have a feature module that requires a string value to be passed to its forRoot static method when imported in app.module.ts, like this: @NgModule({ declarations: [ /* ... */ ], imports: [ My ...

Is it possible to confirm that a value is a valid key without prior knowledge of the object's keys during compile-time?

Is there a way in TypeScript to declare that a variable is a keyof some Record without prior knowledge of the keys? For instance, consider an API response returning JSON data. Is it possible to define a type for the keys of this payload to ensure that whe ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Simple Steps to View Angular Logs in Terminal

Upon initializing my Angular project, I utilized the npm start command to kickstart the application. The console.log() function displays logs exclusively in the browser console window. Is there a way to view these logs in the terminal window? ...

Flux Utils identified an issue stating that the Class constructor App cannot be called without the 'new' keyword

Struggling to set up a Flux Util container for this React component: class App extends React.Component<{},AppState> { constructor(props:Readonly<{}>){ super(props); } static getStores(){ return [ArticlesStore]; } static calcul ...

"Implementing Two-Way SSL with Angular 2 and BrowserSync

Currently, I am working on an Angular2 application that requires two-way SSL authentication. This means that the browser needs to present a valid (PFX) certificate in order to access the application. For deployment, I am using lite-server (which utilizes B ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

"Encountering a Challenge: Cannot Assign Array to ngFor Directive in Ionic App, Displaying

I have encountered an issue while fetching product categories using API. The problem lies in the fact that the categories are being retrieved as an object instead of an Array which is required for *ngFor to work in Ionic. Any assistance on how to define th ...

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...

Module for migration located in a subdirectory

Currently, I am in the process of transitioning an Angular application to NativeScript while utilizing a code-sharing setup. For the migration of Angular modules, I have been executing the following command: ng g migrate-module --name=nameModule However ...

Setting the x-api-key header with HttpInterceptor in Angular 4: A guide

I am attempting to use HttpInterceptor to set the header key and value, but I am encountering the following error: Failed to load https://example.com/api/agency: Response to preflight request doesn't pass access control check: No 'Access ...

Error in Writing Functional Components with Typescript in React

I am struggling to create a versatile functional component and encountering issues like the one shown in this https://i.stack.imgur.com/WQkKg.png: Here is the code snippet: interface IAppTable<Type> { height: number; data: Type[]; tableLayout: ...

Issue with displaying error message and disabling button as Keyup event fails to trigger

Is there a way to assess the user's input in real-time on an on-screen form to ensure that the pageName they enter is not already in the navbarMenuOptions array? If it is, I want to switch the visibility of displayName and displaySaveButton. However, ...

The attribute 'map' is not found on the object of type 'List'

I am currently working on a project that involves lists, each with its own title. However, while using Map, I encountered the following error: Property 'map' does not exist on type 'List' Any suggestions on how to resolve this issue? ...

Preventing direct URL access with Angular redirects after refreshing the page

My website allows users to manage a list of users, with editing capabilities that redirect them to the /edit-user page where form information is preloaded. However, when users refresh the page with F5, the form reloads without the preloaded information. I ...

Using WebSockets in Angular 4

Currently in the process of developing a chat application using Angular 4 and WebSocket. I found guidance from this Angular WebSocket tutorial This is the source code for the WebsocketService: import { Injectable } from '@angular/core'; import ...