尝试从 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);
}
Run Code Online (Sandbox Code Playgroud)
这是 Java rest api(从浏览器调用时工作正常):
@GET
@Path("Trip/Name/{fundId}")
@Produces("text/plain")
public String getTripNameById(@PathParam("tripId") Integer tripId) {
return myDao.getNameById(tripId);
}
Run Code Online (Sandbox Code Playgroud)
我在 chrome 控制台中收到错误消息:
错误:{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: ƒ} 消息:“解析http://localhost:8080/ 时Http 失败...名称:“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);
}
Run Code Online (Sandbox Code Playgroud)
我刚刚添加'到 responseType
HttpClient 默认将响应转换为response.json()。如果您的 API 返回非 json 响应,您必须指定
this.http.get(url, {responseType: 'text'}).
Run Code Online (Sandbox Code Playgroud)
<string>在您的代码中,通过删除返回类型使其工作,使其成为非通用-
return this.http.get(`${this.baseUrl}/Trips/Trip/Name/${tripId}`, httpOptionsPlain);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20010 次 |
| 最近记录: |