【问题标题】:Unexpected token u in JSON at position 0JSON 中位置 0 处的意外标记 u
【发布时间】:2016-09-21 20:52:49
【问题描述】:

当我尝试将字符串转换为对象时,我收到错误 ``:

Unexpected token u in JSON at position 0

服务

setUser : function(aUser){ 
    //sauvegarder User       
    localStorage.setItem('User', JSON.stringify(aUser));
},

getUser : function(){
    //récuperer User      
    return JSON.parse(localStorage.getItem('User'));
}

【问题讨论】:

  • 请显示您要解析的字符串。
  • 您的 http 调用中可能有 dataType : 'json' 或 responseType : 'json'。并且似乎 Angular 无法解析它(因为它不是有效的 JSON 格式)。尝试删除它们。

标签: angularjs json local-storage


【解决方案1】:

首先要做的是查看您要解析的内容。我的猜测是你会发现它是 "undefined",它是无效的 JSON。您收到 undefined 是因为您还没有(还)将任何内容保存到本地存储中的该密钥。然后undefined 被转换为"undefined" 的字符串JSON.parse 无法解析。

我通常像这样在本地存储中存储和检索东西:

存储(就像你的一样)

localStorage.setItem("key", JSON.stringify(thing));

检索(这是不同的)

thing = JSON.parse(localStorage.getItem("key") || "null");
if (!thing) {
    // There wasn't one, do whatever is appropriate
}

这样,我总是在解析一些有效的东西。

【讨论】:

    【解决方案2】:

    您收到此错误是因为您没有将响应作为 JSON 字符串返回,而您的浏览器期望解析 JSON 字符串。因此,它会获取响应字符串的第一个字母并引发错误。

    您可以通过转到浏览器开发工具的网络选项卡并查看响应来验证它。

    要解决此问题,您可以在 http 请求中使用以下代码。

    var promiz = $http.post(url, data, {
          transformRequest: angular.identity,
          transformResponse: angular.identity,
          headers: {
            'Content-Type': undefined
          }
        });
    

    希望这会有所帮助!

    【讨论】:

    • 最佳解决方案,当我从 angularJS 1.2 -> 1.3 升级时工作正常
    【解决方案3】:

    我也遇到了同样的错误。问题是我从 HTTP Get Request 得到的响应不是 JSON 格式,而是纯文本。

    this.BASE_URL = "my URL";
    
    public getDocument() {
        return this.http.get(this.BASE_URL)
          .map((res: Response) => res.json())
          .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }
    

    所以,JSON 解析器抛出了一个错误。

    当我将它映射成这样的纯文本时:

    .map((res: Response) => res.text());
    

    有效。

    【讨论】:

    • Angular 6 升级后不再需要映射到 JSON。 “从 HttpModule 和 Http 服务切换到 HttpClientModule 和 HttpClient 服务。HttpClient 简化了默认的人体工程学(您不再需要映射到 json),现在支持类型化的返回值和拦截器。阅读更多关于 angular.io”跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2019-08-30
    • 2018-01-29
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多