Angular 8错误:HTTP解析过程中的HTTP故障



尝试从Angular 8应用调用服务时会出现错误。这是服务:

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);
  }

这是Java Rest API(从浏览器打电话时工作正常(:

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

我在Chrome Console中遇到错误:

错误:{错误:SyntaxError:json.parse((位于xmlhtt上的json.parse((的json中意外的令牌A…,文本:" AAA BBB CCC"} 标题:httpheaders {normolizedNames:map(0(,lazyupdate:null,lazyinit:ƒ} 消息:" http://localhost:8080/... 名称:" httperrorresponse"

我正在发送纯文本,所以我不是为什么服务尝试解析JSON的原因。

请尝试

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);
  }

我刚刚将'添加到响应型

httpclient(默认情况下(将响应转换为beathess.json((。如果您是API返回非json响应,则必须指定

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

在您的代码中,通过删除<string>返回类型来使其变得非生成 -

return this.http.get(`${this.baseUrl}/Trips/Trip/Name/${tripId}`,  httpOptionsPlain);

最新更新