Angular 8 error: Http failure during parsing for http

23,170

Solution 1

Please try

const httpOptionsPlain = {
  headers: new HttpHeaders({
    'Accept': 'text/plain',
    'Content-Type': 'text/plain'
  }),
  'responseType': 'text'
};

@Injectable()
export class TripService {

public getTripNameById(tripId: number): Observable<string> {
    return this.http.get<string>(`${this.baseUrl}/Trips/Trip/Name/${tripId}`,  httpOptionsPlain);
  }

I've just added ' to the responseType

Solution 2

HttpClient by default converts response to be response.json(). In case you are API returns non-json response, you have to specify that

this.http.get(url, {responseType: 'text'}).

In your code make it non-generic by removing <string> return type for it to work -

return this.http.get(`${this.baseUrl}/Trips/Trip/Name/${tripId}`,  httpOptionsPlain);
Share:
23,170
user2304483
Author by

user2304483

Updated on July 03, 2020

Comments

  • user2304483
    user2304483 almost 4 years

    I get an error when trying to call a service from Angular 8 app. Here is the service:

    const httpOptionsPlain = {
      headers: new HttpHeaders({ 'Accept': 'text/plain',
                                 'Content-Type': 'text/plain'                             
                                 })
    };
    
    @Injectable()
    export class TripService {
    
    public getTripNameById(tripId: number): Observable<any> {
        return this.http.get<any>(`${this.baseUrl}/Trips/Trip/Name/${tripId}`,  httpOptionsPlain);
      }
    

    And here is the Java rest api (works fine when calling from the browser):

    @GET
    @Path("Trip/Name/{fundId}")
    @Produces("text/plain")     
    public String getTripNameById(@PathParam("tripId") Integer tripId) {        
        return myDao.getNameById(tripId);       
    }
    

    I'm getting the error in the chrome console:

    error: {error: SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse () at XMLHtt…, text: "AAA BBB CCC"} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure during parsing for http://localhost:8080/... name: "HttpErrorResponse"

    I'm sending plain text so I'm not why the service try to parse json.

  • user2304483
    user2304483 almost 5 years
    can you fixed the header, i'm getting error "not json format"
  • Tony Ngo
    Tony Ngo almost 5 years
    @user2304483 maybe you are looking for somothing like this ?
  • Ali Celebi
    Ali Celebi over 2 years
    I can confirm that this approach works well to resolve this issue.