Angular HttpClient "Http failure during parsing"

标签 angular typescript angular-httpclient

我尝试从 Angular 4 向我的 Laravel 后端发送一个 POST 请求。

我的 LoginService 有这个方法:

login(email: string, password: string) {
    return this.http.post(`http://10.0.1.19/login`, { email, password })
}

我在我的 LoginComponent 中订阅了这个方法:

.subscribe(
    (response: any) => {
        console.log(response)
        location.reload()
    }, 
    (error: any) => {
        console.log(error)
    })

这是我的 Laravel 后端方法:

...

if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
  return response('Success', 200);
}

return response('Unauthorized', 401);

我的 Chrome 开发工具显示我的请求成功,状态代码为 200。但是我的 Angular 代码触发了 error block 并给我这条消息:

Http failure during parsing for http://10.0.1.19/api/login

如果我从我的后端返回一个空数组,它就可以工作...所以 Angular 正在尝试将我的响应解析为 JSON?我怎样才能禁用它?

最佳答案

您可以使用 responseType 指定要返回的数据不是 JSON。

在您的示例中,您可以使用 textresponseType 字符串值:

return this.http.post(
    'http://10.0.1.19/login',
    {email, password},
    {responseType: 'text'})

responseType 的完整选项列表是:

  • json(默认)
  • 文本
  • 数组缓冲区
  • blob

参见 docs获取更多信息。

关于 Angular HttpClient "Http failure during parsing",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46408537/

相关文章:

typescript 运行时错误 : cannot read property of undefined (enum)

angular - 如果我们不订阅以 Angular 返回可观察对象的 HttpClient 请求,会发生什么

纯文本/文本的 Angular 8/httpclient 错误响应,无法解析响应

angular - Angular 的 @HostBinding( 'window:resize' ) 和 Rxjs 的 fromEvent( window, 'resize' ) 之间的区别

angular - 如何将主体添加到 Angular HttpClient 删除功能

angular - 如何为 Angular 环境使用默认值

typescript - 如何为 TypeScript 定义文件导入文件

javascript - Angular Material Moment.js 格式化

angular - 如何包装 Angular 组件并将 ng-template 从外部组件传递到内部组件

javascript - 将响应映射到模型对象