Angular2: Error in firefox – EXCEPTION: SyntaxError: JSON.parse: unexpected character of the JSON data

Standard

While working with webservices in Angular2 using promises or observable, if you have receive below issue in Firefox browser, it is most likely, you need to set accept header in http get/post request

“EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”

Solution:

You need to append Accept headers to your get request in order for Firefox to render the json that comes back.

In the headers object, the Content-Type specifies that the body represents JSON. The headers object is used to configure the options object. The options object is a new instance of RequestOptions, a class that allows you to specify certain settings when instantiating a request. In this way, headers is one of the RequestOptions.

In the return statement, options is the third argument of the post method, as shown above.

    ngOnInit() {
        let headers = new Headers();
        headers.append('Accept', 'q=0.8;application/json;q=0.9');
        return this.http.get(this.url, { headers: headers } )
                   .map(data => console.log(data.json()))
                   .subscribe(err => console.log(err));
    }

Leave a comment