来自HttpClient POST请求的Angular 6 HTML响应

时间:2018-09-22 18:34:29

标签: angular typescript

我正在尝试进行第三方授权。当我向服务器发送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);
    });

我收到了SyntaxError:

  

JSON中意外的令牌<位于JSON.parse的位置0

2 个答案:

答案 0 :(得分: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调用中的第二个参数。

答案 1 :(得分:0)

我认为放置响应类型的最佳方法是在调用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'});