简体   繁体   中英

Angular 6 HTML response from HttpClient POST request

I am trying to make a third party authorisation. When I hit a POST request to server, it sends HTML as response.

Header

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

API Call

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

I am getting a SyntaxError:

Unexpected token < in JSON at position 0 at JSON.parse

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

Your HTTP options had an extra comma after responseType:'Text'

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

Also, HTTP POST for HttpClientModule takes in payload as second argument within the POST call.

In my opinion the best way to put your response type is when you are calling the http post this will stopped the HttpClient from trying to parse the empty response as a JSON object.

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

with post

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM