Experiencing difficulty accessing the response header in Angular 16 due to CORS restrictions

When attempting to retrieve the response header from my post call, I am encountering difficulties as it appears there are "no headers" or I may be doing something incorrectly.

On the backend, I am utilizing ASP.NET Core. Below is a basic outline of my API:

[HttpPost("myTestApi")]
public async Task<IActionResult> TestAPi([FromBody] TestApiRequestModel requestBody)
{
    await Task.Delay(0);
    Response.Headers.Append("X-Test-Header", "Test Header");
    Response.Cookies.Append("TestCookie", Guid.NewGuid().ToString());
    return StatusCode(200, new { data = requestBody.Input });
}

The configuration for CORS is as follows:

var AngularApp = "AngularApp";
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: AngularApp,
    policy =>
    {
        policy.WithOrigins("http://localhost:4200").AllowCredentials().AllowAnyHeader().AllowAnyMethod();
    });
});

app.UseCors(AngularApp);

Within the Angular app, I have the following code snippet:

public TestAPICall()
{
return this.http.post("https://localhost:7227/api/myTestApi", {input: "xyz"})
.subscribe(
      res => {
        console.log(res);
        console.log(res.headers.get('Set-Cookie'));
      });
}

The variable res retrieves the response data as {"data": "xyz"}, however, I am unable to access the headers. I specifically need to access the custom header TestCookie and the Set-Cookie within the response.

I have attempted various approaches such as defining

TestAPICall():Observable<HttpResponse<any>>
and using post<Response> to try and access headers with res.headers.get("Set-Cookie"), but it always returns undefined. It seems contradictory as post returns an Observable<object>.

Answer №1

To allow access to all APIs, you must include

[EnableCors("AngularApp")]
in the class declaration. Alternatively, to enable a specific API within a controller, add the attribute directly above its function.

[EnableCors("AngularApp")]
[HttpPost("myTestApi")]
public async Task<IActionResult> TestAPi([FromBody] TestApiRequestModel requestBody)
{
    await Task.Delay(0);
    Response.Headers.Append("X-Test-Header", "Test Header");
    Response.Cookies.Append("TestCookie", Guid.NewGuid().ToString());
    return StatusCode(200, new { data = requestBody.Input });
}

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

Tips for making a property non-nullable in Typescript

The Node built-in IncomingMessage type from DefinitelyTyped's definition (used as req in the (req, res, next) arguments) has specified that url can be nullable. This excerpt shows part of the definition: // @types/node/index.d.ts declare module "http ...

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

How can one define a getter within an interface?

One of my classes is structured like this (only showing a portion here): export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t> { public get next(): LinkedListNode<t> { return this._next === thi ...

What is the process for refreshing one observable with data from another observable?

As a complete beginner to these technologies, please bear with me if my question sounds strange and the terminology is not quite right. I have a component that displays data in a table format. export class SourceFieldComponent implements OnInit { ... ...

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

calculating the dynamic height of a document from top to bottom using Angular

Is there a way to dynamically calculate the height of each page from top to bottom in Angular? The syntax that works in JavaScript seems to give an error in Angular. console.log( (document.height !== undefined) ? document.height : document.body.offsetHeigh ...

Having trouble utilizing a function with an async onload method within a service in Angular - why does the same function work flawlessly in a component?

I successfully created a component in Angular that can import an Excel file, convert it into an array, and display its content as a table on the page. The current implementation within the component looks like this: data-import.compoent.ts import { Compo ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

How can you dynamically disable a Menu Item in Angular?

Struggling to implement a functional menu component that allows for disabling specific menu items without cluttering the main application code with excessive menu logic. Is there a way to achieve this without resorting to frequent refreshes or complicated ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Retrieve the interface property following the execution of the HTTP GET service

Having trouble accessing the array properties from my JSON file using the http get service. The goal is to display the Widget array on the web. service.ts: import { Http, Response, Headers } from '@angular/http'; import { Observable } from &apo ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

How can I retrieve image files from locations outside the Angular 5 app or assets directory?

One of the features in my app allows users to upload images. I recently learned that it's best practice to store these image files outside of the app or assets folder since those folders are compiled. Here is a snapshot of my app's folder structu ...

The access token generated by the Angular Keycloak adapter for Spring Boot backend authorization is not valid

The access tokens generated by Angular's keycloak adapter are invalid for communicating with a Spring Boot backend application secured by the same Keycloak realm. The localhost addresses were replaced with example.com to avoid issues with spam filters ...

Can a JavaScript object be created in TypeScript?

Looking for a way to utilize an existing JavaScript "class" within an Angular2 component written in TypeScript? The class is currently defined as follows: function Person(name, age) { this.name = name; this.age = age; } Despite the fact that Java ...

Height transition animation in Angular 2 - maintaining state consistency

I am currently working with an animation code that is linked to my component. animations:[ trigger('slide', [ state('show', style({ height: '*' })), state('hide ...

SQL injection occurs when a malicious statement is injected into the database

I am a junior in SQL and I'm learning about SQL injection, so I have a few questions. My website is developed in ASP.net C#. Let's say I have an HTML Editor where I receive HTML from a client and save it to the database. If someone tries to ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...