Mozilla 无法解析 JSON

Mozilla cant Parse JSON

我的 Angular2 (RC4) 使用以下代码片段从我的 WepApi 获取数据:

getAppointment(id: number): Observable<Event> {
    return this._http.get(this._serviceUrl + 'get/' + id)
        .map(this.extractData)
        .catch(this.handleError);
}

this.extractData 执行以下操作:

private extractData(res: Response) {
        let body = res.json();
        return body || {};
}

这一切在 Chrome、IE、Edge 中都按预期工作,但在 Mozilla 中失败并抛出此错误:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

这又回到了@angluar2/http模块static_response.d.ts。

/**
 * Attempts to return body as parsed `JSON` object, or raises an exception.
 */
json(): any;

因此在 static_response.d.js 中:

/**
 * Attempts to return body as parsed `JSON` object, or raises an exception.
 */
Response.prototype.json = function () {
    var jsonResponse;
    if (http_utils_1.isJsObject(this._body)) {
        jsonResponse = this._body;
    }
    else if (lang_1.isString(this._body)) {
        jsonResponse = lang_1.Json.parse(this._body);
    }
    return jsonResponse;
};

为什么这在 Mozilla 中不起作用? 这是@angular2/http中的错误吗?

Since this is too long for a comment, I added this as an answer - if it doesn't work I'll remove it.


您可以尝试显式添加 Accept header,告诉服务器您期望 JSON 字符串作为响应,这样您就不会意外得到 XML ,像这样:

getAppointment(id: number): Observable<Event> {
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this._http.get(this._serviceUrl + 'get/' + id, options)
        .map(this.extractData)
        .catch(this.handleError);
}

我也遇到了同样的问题。

但我通过更改浏览器配置解决了问题,并且它起作用了。

这样做(这不是正确的方法,但它会起作用)。

在 FF 选项卡中打开 about:config。 比找到 Network.http.accept.default.

值=text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

新值=text/html,application/xhtml+xml,application/JSON;q=0.9,/;q= 0.8