HTTPClient POST 尝试解析非 JSON 响应 [英] HTTPClient POST tries to parse a non-JSON response

查看:25
本文介绍了HTTPClient POST 尝试解析非 JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 中发出请求,我知道 HTTP 响应将不在 JSON 中,而是在文本中.但是,Angular 似乎期待 JSON 响应,因为错误如下:

I'm trying to make a request in Angular and I know that the HTTP response will not be in JSON but in text. However, Angular seems to be expecting a JSON response since the error is the following:

语法错误:意外的标记

在 JSON.parse 的位置 0 处() 在 XMLHttpRequest.c

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.c

以及

解析 http://localhost:9...

这是post方法:

return this.http.post(this.loginUrl, this.createLoginFormData(username, password), this.httpOptions)
  .pipe(
    tap( // Log the result or error
      data => console.log(data);
      error => console.log(error)
    )
  );

和标题.

private httpOptions = {

  headers: new HttpHeaders({
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Content-Type': 'application/x-www-form-urlencoded',
    responseType: 'text'
  },

) };

我认为 responseType: 'text' 足以让 Angular 期待一个非 JSON 响应.

I thought that responseType: 'text' would be enough to make Angular expect a non JSON response.

推荐答案

您将 responseType: 'text' 放在了 httpOptions 的错误部分 - 它应该坐在headers外面,像这样:

You've put responseType: 'text' in the wrong section of your httpOptions - It should sit outside of headers, like so:

private httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Content-Type': 'application/x-www-form-urlencoded'
  }),
  responseType: 'text'
};

根据您之前的情况,responseType 的请求标头被发送到服务器,而不是简单地向 Angular 发出指令以实际将响应视为文本.

With what you had before, a request header of responseType was being sent to the server, rather than simply having an instruction to Angular to actually treat the response as text.

这篇关于HTTPClient POST 尝试解析非 JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆