Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 error: Http failure during parsing for http

Tags:

angular

rxjs

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.

like image 322
user2304483 Avatar asked Jul 03 '19 06:07

user2304483


2 Answers

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

like image 173
MoxxiManagarm Avatar answered Nov 15 '22 02:11

MoxxiManagarm


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);
like image 30
Uday Vunnam Avatar answered Nov 15 '22 04:11

Uday Vunnam