我在WebAPI中使用CORS支持并从EntityManager获取一个奇怪的结果集,即使我从服务器获取状态代码200和数据。响应得到
错误消息是(截断):
{message: "; ", statusText: "OK", status: 200, url:"http://localhost:61808/odata/Servers?$filter=Id%20gt%2080&$top=20&$expand=Owner%2CApplications"}
我的datacontext:
(function () {
angular.module('App').factory('datacontext', datacontext);
datacontext.$inject = ['EntityManagerFactory'];
function datacontext(EntityManagerFactory) {
var EntityQuery = breeze.EntityQuery;
var Manager = EntityManagerFactory.newManager();
return {
getServers: getServers
};
function getServers() {
return EntityQuery
.from('Servers')
.expand('owner, applications')
.where('id', 'gt', 80)
.take(20)
.toType('server')
.using(Manager)
.noTracking()
.execute()
.then(success)
.catch(error);
}
function success(response) {
return response.results;
}
function error(error) {
console.log(error);
}
我的WebAPI web.config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, DataServiceVersion, MaxDataServiceVersion" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS, MERGE" />
</customHeaders>
</httpProtocol>
此代码在Internet Explorer中运行良好。但是,即使有效负载已交付,Chrome中也会出现错误!有什么想法吗?
答案 0 :(得分:1)
当前版本的datajs 1.1.2中存在一个错误,该错误是根据https://datajs.codeplex.com/workitem/756上的codeplex问题提交的。
在datajs.js中,将readResponseHeaders替换为:
var readResponseHeaders = function (xhr, headers) {
/// <summary>Reads response headers into array.</summary>
/// <param name="xhr" type="XMLHttpRequest">HTTP request with response available.</param>
/// <param name="headers" type="Array">Target array to fill with name/value pairs.</param>
var responseHeaders = xhr.getAllResponseHeaders().split(/\r?\n/);
var i, len;
for (i = 0, len = responseHeaders.length; i < len; i++) {
if (responseHeaders[i]) {
var header = responseHeaders[i].split(": ");
headers[header[0]] = header[1];
}
}
// Fix to handle Firefox CORS bug
var requiredHeaders = [
'Content-Type', 'DataServiceVersion'
/*, 'Content-Length'
, 'Cache-Control'
, 'Access-Control-Expose-Headers'
, 'X-Content-Type-Options'
, 'Date'*/
];
for (i = 0; i < requiredHeaders.length; i++) {
if (headers[requiredHeaders[i]] === undefined &&
xhr.getResponseHeader(requiredHeaders[i])) {
headers[requiredHeaders[i]] = xhr.getResponseHeader(requiredHeaders[i]);
}
}
};
并在WebAPI的web.config中添加:
<add name="Access-Control-Expose-Headers" value="DataServiceVersion" />