【问题标题】:Angular 8 error: Http failure during parsing for httpAngular 8 错误:解析 http 期间的 Http 失败
【发布时间】:2019-11-13 18:55:54
【问题描述】:

尝试从 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 JSON.parse () at XMLHtt…, text: "AAA BBB CCC"} 标头:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} 消息:“http://localhost:8080/ 解析期间的 Http 失败... 名称:“HttpErrorResponse”

我发送的是纯文本,所以我不是服务尝试解析 json 的原因。

【问题讨论】:

标签: angular rxjs


【解决方案1】:

请尝试

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 中添加了'

【讨论】:

  • 你能修复标题吗,我收到错误“不是 json 格式”
  • @user2304483 也许您正在寻找类似this 的东西?
【解决方案2】:

HttpClient 默认将响应转换为 response.json()。如果您是 API 返回非 json 响应,则必须指定

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

在您的代码中,通过删除 &lt;string&gt; 使其工作的返回类型使其成为非泛型 -

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

【讨论】:

  • 我可以确认这种方法可以很好地解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2019-05-13
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多