尝试从 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 控制台中收到错误消息:
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"
我正在发送纯文本,所以我不是为什么服务尝试解析 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);
}
我刚刚添加了
'
到 responseType
关于 Angular 8 错误 : Http failure during parsing for http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56864107/