简体   繁体   中英

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM