【问题标题】:Angular 6 HTML response from HttpClient POST request来自 HttpClient POST 请求的 Angular 6 HTML 响应
【发布时间】:2019-12-20 11:07:18
【问题描述】:

我正在尝试进行第三方授权。当我向服务器发送 POST 请求时,它会发送 HTML 作为响应。

标题

private httpOptions = {
    headers: new HttpHeaders({
        'Accept': 'text/html',
        'Content-Type': 'application/json'
}),
    responseType: 'text',
};

API 调用

return this.http.post(this.authUrl, this.httpOptions)
    .subscribe(data => {
        console.log(data);
    });

我收到一个语法错误:

JSON.parse 中位置 0 处的 JSON 中的意外标记

【问题讨论】:

  • 您缺少 http 正文参数

标签: angular typescript


【解决方案1】:
 private httpOptions = {
    headers: new HttpHeaders({
        'Accept': 'text/html',
        'Content-Type': 'application/json'
    }),
    responseType: 'text'
};

您的 HTTP 选项在 responseType:'Text' 之后多了一个逗号

return this.http.post(this.authUrl,null, this.httpOptions)
        .subscribe(data => {
            console.log(data);
        });

另外,HttpClientModule 的 HTTP POST 将负载作为 POST 调用中的第二个参数。

【讨论】:

  • "您的 http 选项在 responseType:'Text' 后多了一个逗号"。它仍然是有效的代码。
【解决方案2】:

在我看来,放置响应类型的最佳方式是在调用 http 帖子时,这将阻止 HttpClient 尝试将空响应解析为 JSON 对象。

 this.http.put(
 url,
 data,
 {
    headers: new HttpHeaders().set('Content-Type', 'application/json'),
    responseType: 'text' 
 }
 ).subscribe(  ....   );

有帖子

return this.http.post(url, params, {headers : headers, withCredentials : true,responseType: 'text'});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 2023-03-16
    • 2015-06-28
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多