【问题标题】:Angular 8 - Http post return error when is not errorAngular 8 - 不是错误时的Http post返回错误
【发布时间】:2019-10-27 20:40:41
【问题描述】:

我尝试向 API 发出 http post 请求。 问题如下:API 返回 200 状态码,即成功请求。但在我的代码中,就像在 http 中一样,出现了错误。

我的服务代码:

  getUsers(data) {
      const httpOptions = {
      headers: new HttpHeaders({
        "Accept": "application/json"
      })
      };

      let input = new FormData();
      input.append('firstName', data.firstName);

      return this.http.post('http://localhost/post.php', input, httpOptions);
    }

我的组件代码:

callApi(data) {
    this.userService.getUsers(data)
    .subscribe(
      (data) => { // Success
        console.log(data)
      },
      (error) => {
        console.error("Error: " + JSON.stringify(error));
      }
    );
  }

浏览器返回:

http 发帖结果

可能是什么问题?

【问题讨论】:

  • 你能把你在 JSON.stringify(error) 中看到的东西贴出来吗;
  • @Sajeetharan 我更新了帖子。截图在这里:i.stack.imgur.com/M3UPH.png

标签: angular http


【解决方案1】:

您需要使用responseType指定要返回的数据不是JSON。在您的代码中,您可以使用文本的responseType字符串值,如下所示:

return this.http.post(
    'http://localhost/post.php',
    {responseType: 'text'})

【讨论】:

  • 我尝试过,但它返回一个 CORS 错误。我需要检查一下
  • 从另一个域调用时,您可能需要在后端启用 cors,因为这实际上会引发错误或任何其他后端错误
猜你喜欢
  • 2019-12-03
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
相关资源
最近更新 更多