生产模式下的 Angular 项目错误:SyntaxError: Unexpected token { in JSON at position 65

时间:2021-03-26 05:54:40

标签: javascript json angular typescript production

我需要这方面的帮助。可能这是愚蠢的,但经过数小时的调查,我看不出问题所在。 我有一个 angular 10 项目。这是后端(php中的api):

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

    echo json_encode($result);
});

它返回这个json:

{
    "status":"success",
    "code":200,
    "data":
    [
        {
            "id":"1",
            "nombre":"Gazpacho tradicional",
            "marca":"Hacendado",
            "puntuacionYuca":"90\/100",
            "puntuacionCoco":"9\/10",
            "puntuacionMyReal":"Buen procesado",
            "mediaVagana":"9",
            "imagen":"gazpacho-hacendado.jpg",
            "supermercado":"Mercadona",
            "comentario":"Saludable en otras marcas"
        }
    ]
}

我已经在几个网站上检查过 json 并且它是有效的。

这是angular service.ts中的代码:

getProductosVaganos(){
        return this._http.get(this.urlvaganos+'productos-vaganos').pipe(map((response: any) => response.json()));
    }

这是angular component.ts中的代码:

getProductosVaganos(){
        this._productoVaganoService.getProductosVaganos().subscribe(
            result => {
                if (result.code != 200){
                    console.log(result);
                }else{
                    this.productosVaganos = result.data;
                }
            },
            error => {
                console.log(<any>error);
            }
        );
    }

它在本地开发模式下完美运行。但是当我编译项目并将其部署在托管的 public_html 文件夹中时,它会在 component.ts 函数中返回此错误:

list.component.ts > getProductosVaganos() > 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)

public_html 文件夹中的结构与本地相同。

我已经测试了 JSON.stringify() 和 JSON.parse() 方法,但没有找到解决方案。 我也测试了删除 service.ts 方法中行尾的 .json()。在这种情况下,当我在 chrome 中调试时,在生产中,它进入 component.ts 方法的“result”内部,但 result.data 元素是“undefined”。

我认为问题出在本地和生产之间,因为它们有不同的语言,本地的打字稿和编译的 javascript,在生产中,但我不知道如何解决它。

任何帮助将不胜感激。

问候。

2 个答案:

答案 0 :(得分:0)

看来 response 有完整的回复。尝试将 {observe: 'body'} 明确写成如下。

getProductosVaganos(){
    return this._http.get(this.urlvaganos+'productos-vaganos', {observe: 'body'}).pipe(map((response: any) => response.json()));
}

答案 1 :(得分:0)

我发现了错误。我在 API 中有一些用于 Google Recaptcha 的代码,在包含连接到数据库的代码的同一个文件中。此 google Recaptcha 代码失败,并以 JSON 格式抛出错误。这段 JSON 位于响应的开头,因此解析器无法正确读取响应数据的一部分。 评论这个 Recaptcha 代码,网络运行正常。 问候。

相关问题