Angular HttpClient"解析过程中的Http失败"

nut*_*tzt 80 typescript angular angular-httpclient

我尝试将Angular 4的POST请求发送到我的Laravel后端.

我的LoginService有这个方法:

login(email: string, password: string) {
    return this.http.post(`http://10.0.1.19/login`, { email, password })
}
Run Code Online (Sandbox Code Playgroud)

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

.subscribe(
    (response: any) => {
        console.log(response)
        location.reload()
    }, 
    (error: any) => {
        console.log(error)
    })
Run Code Online (Sandbox Code Playgroud)

这是我的Laravel后端方法:

...

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

return response('Unauthorized', 401);
Run Code Online (Sandbox Code Playgroud)

我的Chrome开发工具说我的请求是成功的200状态代码.但我的Angular代码触发了error阻止并给了我这条消息:

解析http://10.0.1.19/api/login期间的Http失败

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

Kir*_*kin 169

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

在您的示例中,您可以使用responseType字符串值text,如下所示:

return this.http.post(
    'http://10.0.1.19/login',
    {email, password},
    {responseType: 'text'})
Run Code Online (Sandbox Code Playgroud)

其他选项是json(默认),arraybufferblob.

有关更多信息,请参阅文档.

  • @Tanzeel请查看我的答案:/sf/answers/4870776011/ (2认同)

Mar*_*ndl 82

我只是想补充一点,您必须省略get/post 方法 ( ) 上的通用参数.get<T>

\n

\xe2\x9c\x94\xef\xb8\x8f 这将起作用:

\n
this.http.get(`https://myapi.com/health`, {responseType: 'text'})\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x9d\x8c 这不起作用

\n
this.http.get<string>(`https://myapi.com/health`, {responseType: 'text'})\n
Run Code Online (Sandbox Code Playgroud)\n

后者会产生错误:

\n
\n

预期类型来自属性“responseType”,该属性在类型“{ headers?: HttpHeaders | ”上声明\n { [标题:字符串]:字符串 |\n字符串[]; } | 不明确的; 观察:“事件”;上下文?: HttpContext |\n未定义;参数?:HttpParams | { ...; } | 未定义;\nreportProgress?: boolean | 不明确的; 响应类型?:“json”|\nundefined; withCredentials?: 布尔值 | 不明确的; }'

\n
\n

  • @FatihErsoy,因为没有接受泛型和两个参数的方法重载 (2认同)

Trầ*_*iệp 13

如果你有选择

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })
Run Code Online (Sandbox Code Playgroud)

  • 一个解释会很有帮助。http.post 最多允许三个参数 - 如果我还需要添加标头怎么办? (3认同)

小智 6

即使添加了 responseType,我也处理了几天没有成功。最后我明白了。确保在您的后端脚本中您没有将标头定义为 -("Content-Type: application/json);

因为如果你把它变成文本但后端要求 json,它会返回一个错误......