HTTP Interceptor error "HTTP failure during parcing" on Post request

Viewed 26

I have an http interceptor for all of my api calls that catches errors and also catches items for local storage to download. All of my api calls except 1 return JSON. The 1 api call that does not is returning a string. I am getting a "failure to parse" error message with that api call from the interceptor even though my post request is requesting responseType to be text. I am connecting to a Spring backend that I cannot modify, so I need to fix this in Angular. Is there a way to have the interceptor check if the expected response type is text and not throw that error for the 1 call, but otherwise throw the error if the response type should be JSON?

api service:

refreshDetails():Observable<any>{
     return this.http.post('../app/refreshDetail', {responseType: 'text'})
}

http interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>>{
     this.totalRequests ++
     this.loaderService.show()
     return next.handle(request)
        .pipe(
          timeout(30000),
            tap(
              event=> {
                if(instanceOf HttpResponse){
                  let contentDisposition = event.headers.get('content-disposition')
                  if(contentDisposition !== undefined && contentDisposition !== null){
                    let c = contentDisposition.split(':')
                    if(c[1]!== undefined && c[1] !== null){
                      let c1=c[1]].trim().split('=')
                      if(c1[1]!== undefined && c1[1] !== null){
                        let filename = c1[1].trim().replace(/['"]+/g,'').toString()
                        if(filename !== undefined && filename !== null){
                          localStorage.setItem("downloadFileName", filename)
                        }
                      }
                    }
                  }
                }
              },
            (error: HttpErrorResponse)=> {
               console.log(error)
             }
            ),
            catchError((error: HttpErrorResponse) => {
               return throwError(error)
            }),
            finalize(()=> {
              this.totalRequests --
              if(this.totalRequests === 0) {
                 this.loaderService.hide()
              }
            })
          )
     }
 
1 Answers

So it turns out, if you don't have a Body, the request gets turned into the body.

refreshDetails():Observable<any>{
 return this.http.post('../app/refreshDetail', {}, {responseType: 'text'})
}

Just needed an empty object to send as the body to get the request headers to read the response type as text. interceptor was doing its job after all and not changing the response type.

Related