Error encountered in Angular production mode: JSON parsing issue at position 65 with unexpected { token

Seeking assistance with a perplexing issue I've encountered after extensive investigation. Despite my efforts, the problem remains elusive.

I am working on an Angular 10 project with a PHP backend API:

...
$result = array(
        'status' => 'success',
        'code'   => 200,
        'data'   => $products
    );

    echo json_encode($result);
});

The JSON response is as follows:

{
    "status":"success",
    "code":200,
    "data":
    [
        {
            "id":"1",
            "name":"Traditional Gazpacho",
            "brand":"Hacendado",
            "yuccaScore":"90\/100",
            "cocoScore":"9\/10",
            "myRealScore":"Good processing",
            "veganRating":"9",
            "image":"gazpacho-hacendado.jpg",
            "supermarket":"Mercadona",
            "comment":"Healthier in other brands"
        }
    ]
}

Validation tests confirm the JSON's correctness.

This is the code within the Angular service.ts file:

getVeganProducts(){
        return this._http.get(this.urlvaganos+'vegan-products').pipe(map((response: any) => response.json()));
    }

And here is the code from the Angular component.ts file:

getVeganProducts(){
        this._veganProductService.getVeganProducts().subscribe(
            result => {
                if (result.code != 200){
                    console.log(result);
                }else{
                    this.veganProducts = result.data;
                }
            },
            error => {
                console.log(<any>error);
            }
        );
    }

This setup functions flawlessly in local development mode. However, upon deployment to the public_html directory on the hosting server, an error arises within the component.ts function:

list.component.ts > getVeganProducts() > error:  SyntaxError: Unexpected token { in JSON at position 65
    at JSON.parse (<anonymous>)
    at gd.json (main.99255eee2d008be2c609.js:1)
    at O.project (main.99255eee2d008be2c609.js:1)
    at O._next (main.99255eee2d008be2c609.js:1)
    at O.next (main.99255eee2d008be2c609.js:1)
    at XMLHttpRequest.s (main.99255eee2d008be2c609.js:1)
    at l.invokeTask (polyfills.35a5ca1855eb057f016a.js:1)
    at Object.onInvokeTask (main.99255eee2d008be2c609.js:1)
    at l.invokeTask (polyfills.35a5ca1855eb057f016a.js:1)
    at a.runTask (polyfills.35a5ca1855eb057f016a.js:1)

The directory structure in public_html mirrors that of the local environment.

I have experimented with JSON.stringify() and JSON.parse(), yet the solution evades me. Removing .json() from the service.ts method yielded undefined results for result.data when debugging in Chrome in production.

The disparity between local TypeScript and compiled JavaScript in production appears to be the root cause, but resolving it eludes me.

Any guidance or insights would be greatly appreciated.

Thank you.

Answer №1

It appears that the response contains all the necessary data. Make sure to specify {observe: 'body'} explicitly in your code as shown below.

getVeganProducts(){
    return this._http.get(this.urlvegan+'vegan-products', {observe: 'body'}).pipe(map((response: any) => response.json()));
}

Answer №2

After some troubleshooting, I discovered the issue. There was a section of code related to Google Recaptcha within the API file that also contained the database connection code. This Recaptcha code was causing errors and producing a JSON error format in the response. The JSON snippet appeared at the start of the response data, causing the parser to misinterpret the following data. By commenting out the Recaptcha code, the website now functions properly. Best regards.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I remove the currently clicked div element in HTML using Angular 4?

Here is the content of my div tag deleteObject(event) { console.log(event); console.log(event.target); event.target.hidden = true; //event.target.classList.add('class3'); } <div class="col" (click)="deleteObject($event)"&g ...

Leveraging Express request-specific variables to facilitate logging with correlation IDs

Our node express app is now incorporating correlation id's to link requests together. These id's are sent in the header from other services, and our middleware captures them, creates a bunyan logger with the id, and includes it in the request obj ...

Implementing serverside pagination using Datatable in Javascript: Passing POST request body data

Attempting to incorporate ServerSide pagination using Datatable for AJAX POST request The Javascript Code snippet below showcases the issue faced when utilizing JSON.stringify for data field, causing the API not to be triggered. $('#tripboard_table&a ...

The JSONModel does not yield any results

I am utilizing JSONModel to retrieve JSON data from a specified URL. This object is quite basic, with only two strings - "name" and "url". Initially, I created the Object Model: @protocol Tutorial @end @interface Tutorial : JSONModel @property (nonatomic ...

Having trouble getting angular-masonry to function properly as it keeps throwing an error saying it does not recognize the method 'imagesLoaded'

I am currently attempting to integrate the angular-masonry plugin by passy with an infinite scroll directive, but I'm encountering some issues. I have set up a plunk for this here. The console is displaying an error message that reads "TypeError: Obje ...

Using jQuery to navigate to a different webpage

Imagine a scenario where there is a page responsible for inserting data into a database This page can be referred to as page1.php //INSERT CODE //HTML FORM Every time page1.php is accessed, the URL displayed at the top looks like this www.abc.com/page ...

Side Panel Extending Off Screen Upon Resizing

I'm encountering an issue with the sidebar on my HTML page. The problem arises when I click the 'Upload Data' button, causing the sidebar's header to extend beyond the screen if I resize the window. The only way to fix this is by refres ...

What is the best way to handle JSON parsing and writing in C++?

Can someone provide guidance on reading and writing a JSON file in C++? I am planning to use the file to store player information and settings for a simple number guessing game I'm developing. It's a basic console game, but it will help me learn ...

Javascript-created HTML elements are failing to display on the webpage

As a newcomer to javascript, I am trying to dynamically create HTML elements using javascript for a class project. However, I am facing an issue where nothing is displaying on my page. Any help or guidance on what I might be missing would be greatly apprec ...

Streamlining with jQuery Mobile and JSON data

Hello everyone, I have a few inquiries about implementing jQuery Mobile and JSON. I am interested in developing a mobile application for a website that currently doesn't have a JSON plugin installed, and I have these two specific questions: How can ...

Troubleshooting type casting issue in Typescript when working with objects containing getters and setters

I'm facing an issue with the code snippet provided. I suspect it might be related to casting, but I'm unable to pinpoint the exact solution. interface Code { code: string; expiration: number; } interface IActivationCode { [userId: string] ...

Retrieving query strings from a website's GET request using tools other than Selenium

Objective: I am currently conducting testing on a particular website to verify the validity of key-value pairs that are being sent. I am seeking a way to extract the queryString parameters (key-value pairs) from a GET request made to a website. These quer ...

Having trouble accessing multiple items in JSON format using AsyncStorage in React Native

After attempting to retrieve all items stored in my AsyncStorage, I encountered an issue where the response was not in JSON format. Instead, it was returned in a different format: [["engineyard", "{\"login\":\" ...

Using Bootstrap CSS and JavaScript specifically for carousel functionality

Custom Styles and Scripts for Bootstrap Carousel Using Carousel with Controls https://getbootstrap.com/docs/4.0/components/carousel/ <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner ...

What could be the reason for the malfunction of Bootstrap Js in my template?

This question focuses on understanding how something works rather than just fixing it. I really enjoy learning about this. Currently, I am involved in a project that combines VueJS and Symfony. One of the things I would like to achieve is using Bootstrap ...

How can you use Knex to order the results for each WHERE clause in a SELECT query?

When querying a database using knex, the desired results should be ordered in a specific manner. The current code provides the required results but lacks the expected order. knex("FRUITTBL") .select("FruitTag", "FruitName", ...

Is there a way to verify if an object is a regular expression in different V8 contexts?

It came to my attention that utilizing the raw regular expression syntax in a V8 context, leads to a situation where instanceof RegExp returns false even with a shared global RegExp object between contexts. var Contextify = require('contextify') ...

Refreshing Angular navigation directive post user authentication

As I delve into mastering AngularJS and embark on my inaugural "real" project, I find myself at a crossroads. Despite hours of scouring the internet in search of answers, I have yet to stumble upon a suitable solution that speaks to me in layman's ter ...

How can one authenticate an express session when sending a POST request?

Is there a way to verify that a user is sending a post request in order to prevent unauthorized posting to a URL? I am currently using express-session for this purpose, but I'm open to exploring alternative methods as well. I attempted to implement t ...

Utilizing Ajax looping to generate dynamic HTML content with Bootstrap tabs

I am looking for a way to fetch multiple JSON files and display the data from each file in separate Bootstrap 3 Tabs. I understand that the getJSON function does not wait for completion before moving on, but I need help with using callbacks in situations ...