Macryo
Macryo

Reputation: 188

Angular How to check HttpRequest object to set proper content-type for headers?

My team is working for some time on rewriting front-end of our application to Angular. Everything was going more or less smoothly until I encountered file importing views. Our default HttpHeaderEnricherInterceptor is setting default Content-Type as application\json. It works well in the whole application but while trying to import any file all I get is 415. However, if I remove .set('Content-Type', 'application/json') importing is working properly... but all other components are failing. I was trying to make some if statements based on HttpRequest params but it doesn't recognize has() method and some others that I've tried.

I know that final option to solve this is to set content-type on each request but it's something I would like, better avoid it as we decided to try finding global solution to the problem.

Here's my intercept() code:

import { TokenService } from './../token/token.service';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HttpHeaderEnricherInterceptor implements HttpInterceptor {

  constructor(private tokenService: TokenService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(`${req.url}?${req.params.toString()}`);

    const changedReq = req.clone(
      {headers:  req.headers
        .set('Authorization',  this.tokenService.getToken() || '')
        .set('Content-Type', 'application/json')
      });
    return next.handle(changedReq);
  }
}

Thanks for any tips!

Upvotes: 1

Views: 1186

Answers (1)

kemsky
kemsky

Reputation: 15270

Looks like there is already opened issue on Github: https://github.com/angular/angular/issues/19730

Workarounds are possible but ugly, i.e. global boolean flag switching before and after call, adding fake header as indicator i.e.:

if(headers.get('X-Set-Content-Type') != null){
    headers.set('Content-Type', 'application/json')
}

Upvotes: 1

Related Questions