【问题标题】:Aurelia | json parse uncaughtable exception?奥里利亚 | json解析无法捕获的异常?
【发布时间】:2016-07-23 02:45:46
【问题描述】:

所以我正在尝试按照 aurelia 文档提出这个帖子请求: http://aurelia.io/hub.html#/doc/article/aurelia/fetch-client/latest/http-services/3

这是请求:

 httpClient.configure(config => {
        config
            .withBaseUrl(baseUrl)
    });
this.client = httpClient;
this.client.fetch(`/api/Register/${userName}`, {
            method: "post",
            body: json(loginInformation),
            headers: {
                'Access-Control-Allow-Origin' : '*',
                'Accept': 'application/json'
            }
        }) .then(response => this.safelyParseJSON(response))
            .then(data => this.setup(data));

safetyParseJSON 在哪里:

    safelyParseJSON(response) {
        var parsed
            try {
                parsed = response.json();
            } catch (e) {
            }

        return parsed 
    }

但我一直收到此错误:

“未捕获(承诺中)SyntaxError:JSON 输入意外结束”

有人知道我做错了什么吗?

注意: 我仅在从服务器接收 404 / 500 时收到此错误,如果结果正常,则此方法有效。

注意 2:我将这个函数包装在 try-catch 中,但这仍然不起作用,它没有捕获异常。

注意3:我已经尝试替换这一行:

parsed = response.json();

用这一行:

parsed = JSON.parse(response);

但是响应总是未定义的。

【问题讨论】:

  • 返回的 json 是什么样的?检查开发工具中的网络选项卡。

标签: javascript jquery json aurelia


【解决方案1】:

在调用.json()之前检查响应状态:

.then(response => {
  if (response.ok) {
    return response.json().then(data => this.setup(data));
  }
  return Promise.reject(response.text());
});

【讨论】:

    【解决方案2】:

    我最终使用了 Jeremy Danyow 的答案,但做了一点小改动:

    .then(response => {
     if (response.ok && response.status === 200) {
       return response.json().then(data => this.setup(data));
     }
     return Promise.reject(response.text());
    });
    

    在我的情况下添加 response.status 检查是必要的,因为 response.ok 对于状态代码 204(无内容)也是如此。

    【讨论】:

    • 我个人不会在 204 响应状态上抛出任何错误,这通常是一种 DELETE 方法,不是一个糟糕的响应,而是一个不包含任何信息的好响应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多