【发布时间】:2017-05-22 16:34:04
【问题描述】:
我有一个与 Api 通信的 Angular 应用程序,我在其中添加 JSON 响应前缀,该响应仅由 )]}', 的数组组成,正如 angular's official documentation 建议的那样。
问题是,我的浏览器似乎试图在 angular 之前解码响应。
我在调试器中一步一步走,在xhr.onload回调被触发后,响应已经null。
我说的代码是这个:
// From angular.js(1.5.9):12122
xhr.onload = function requestLoaded() {
var statusText = xhr.statusText || '';
// responseText is the old-school way of retrieving response (supported by IE9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
var response = ('response' in xhr) ? xhr.response : xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
}
completeRequest(callback,
status,
response,
xhr.getAllResponseHeaders(),
statusText);
};
}
xhr.response 在 Angular 做任何事情之前为空(我认为)。
Angular 尝试使用此代码去除前缀:
function defaultHttpResponseTransform(data, headers) {
if (isString(data)) {
// Strip json vulnerability protection prefix and trim whitespace
var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
}
}
}
return data;
}
但此时数据绝不是字符串,浏览器已经尝试对其进行解码(但失败了)。
Api 的输出如下所示:
)]}',
[{"name": "A"},{"name": "B"}]
如果我删除前缀,它可以正常工作。我试过了: - 歌剧 45.0 - 火狐 46 - 铬 58
它们的行为都相似,所以我可能遗漏了一些东西。
响应头包含以下内容:
HTTP/1.1 200 OK
Server: nginx/1.11.5
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Cache-Control: no-cache, private
[...]
Content-Length: 1793
有什么想法吗?
非常感谢。
【问题讨论】:
-
为什么你的 xhr.response 为空?您的 api 是否返回空响应?
-
是的,它正在工作..我在搜索时未能找到这个问题..无论如何,您能发布一个答案以便我接受吗?这将增加其他有相同问题的人找到答案的机会。顺便说一句,感谢您的帮助。
-
当然。很高兴它奏效了。只是希望我们能感谢原作者。
标签: javascript angularjs json security xss