angularangular-httpclientangular-http

Setting HTTP Headers in Angular 13 does not seem to work right


If I have my headers set like this then I get a 415 returned from my API because the HTTP Request is sent with a content-type of text/plain

let headers: HttpHeaders = new HttpHeaders();

If I place the code below then somehow it messes up the Origin header because I get a CORS violation again after having already resolved that before working on this problem.

if (!headers.has('content-type')) {
    headers = headers.append('content-type', 'application/json')
}
else{
    headers = headers.set('content-type', 'application/json')
}

Everything I've found makes it seem like I'm setting the headers properly, but I can't explain why I'm running into these issues.

Any ideas?

Package.json dependencies:

    "@angular/animations": "~13.0.0",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "bootstrap": "^5.1.3",
    "jquery": "^3.6.0",
    "popper": "^1.0.1",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },

Solution

  • I wound up needing to adjust my API to allow Content-Type headers in the pre-flight calls.

                services.AddCors(options =>
                {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins(Configuration.GetValue<string>("smWebUrl"));
                        builder.WithHeaders("Content-Type");
                    });
                });