Angular 8 error: Http failure during parsing for http

 ̄綄美尐妖づ 提交于 2021-01-23 04:33:30

问题


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.


回答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




回答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);


来源:https://stackoverflow.com/questions/56864107/angular-8-error-http-failure-during-parsing-for-http

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!