【问题标题】:Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid JSONAngular 6:SyntaxError:JSON.parse 中位置 0 处的 JSON 中的意外标记 O 具有有效的 JSON
【发布时间】:2019-11-15 07:42:30
【问题描述】:

我不知道是我的函数错了,应该是向服务器发送数据,还是服务器上的函数错了。 我查找了类似的问题,但我对我的问题采用的解决方案不起作用。

我的函数如下所示:

postData(number){
   let array = JSON.stringify(this.locArr);
   return this.http.post<any>(this.url, array)
    .subscribe(),
    error => console.log("Error: ", error)
    }

发送的 JSON:

[ 
  { 
      "id":222,
      "name":"Lars",
      "sLA":37
   },
  { 
      "id":223,
      "name":"Sim",
      "sLA":12
   }
]

服务器函数接收到所有参数,如令牌等,但我上面写的数组为空,尽管它是有效的 json。 我想知道为什么会出现这个错误。

感谢任何建议

【问题讨论】:

  • 这个 json 无效。请检查您的 json:jsonlint.com
  • 对不起,我改了,忘了去掉昏迷。现在它应该是有效的 json。
  • 您还向服务器发布了一个数组,该数组不是有效的 json 或更像文本。您应该将其发布为 json 对象
  • 我不确定你的意思。上面的数组是有效的 json?我用验证器检查了它,还是你的意思是别的?
  • 我尝试使用 Object.assign 并将其作为 JSON 对象发送,但它仍然无法正常工作..

标签: json angular http-post


【解决方案1】:

本地数组会被Angular自动转换成JSON,你不需要字符串化或解析它。

postData(number){
    this.http.post<any>(this.url, this.locArr)
    .subscribe((data)=>{
        //code after receiving data from server
    },
        error => console.log("Error: ", error))
}

【讨论】:

    【解决方案2】:

    我相信你正在使用httpClientModule,所以你不需要JSON.stringify删除这一步JSON.stringify(this.locArr);
    您还需要将其作为json对象{}而不是json数组[]发送

    postData($locArr){ // pass the array to the service function
       let data = { data : $locArr}; // note that you have to post it as json object {} not []
       return this.http.post<any>(this.url,data);
    }
    

    【讨论】:

    • @Cara 请检查一下
    • 您好,谢谢您的回答!我认为这是服务器端错误。我会试试的!
    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多