我试图从
angularjs项目中使用Redmine API.
我最终使用jsonp来解决CORS问题.
我打电话给这个时收到404:
var url = 'http://muser:mpasswd@myredmine/issues.json?callback=displayIssues'; $http({ method: 'JSONP',url: url }). success(function (data,status) { console.log("success"); console.log(data); }). error(function (data,status) { console.log("Error: " + status); }); ... function displayIssues(issues) { console.log('displayIssues'); ... }
但是当我用Postman调用相同的URL时,它可以工作.
为什么我会收到这个404?
这是我的控制台:
GET http://muser:mpasswd@myredmine/issues.json?callback=displayIssues jsonpReq @ angular.js:8576(anonymous function) @ angular.js:8420sendReq @ angular.js:8291serverRequest @ angular.js:8025wrappedCallback @ angular.js:11498wrappedCallback @ angular.js:11498(anonymous function) @ angular.js:11584Scope.$eval @ angular.js:12608Scope.$digest @ angular.js:12420Scope.$apply @ angular.js:12712(anonymous function) @ angular.js:18980x.event.dispatch @ jquery-2.0.3.min.js:5y.handle @ jquery-2.0.3.min.js:5 authentication.service.js:100 Error: 404
Rest API和jsonp都在admin-> setting-> auth中启用
我也尝试过:
var url = 'http://muser:mpasswd@myredmine/redmine/issues.json&callback=JSON_CALLBACK'; $http.jsonp(url,{ params: { callback: 'JSON_CALLBACK',format: 'json' } }).success(function (data) { console.log('ok'); }).error(function (data) { console.log('error: ' + JSON.stringify(data)); });
得到这个:
GET http://muser:mpasswd@myredmine/issues.json&callback=angular.callbacks._0?callback=JSON_CALLBACK&format=json jsonpReq @ angular.js:8576(anonymous function) @ angular.js:8420sendReq @ angular.js:8291serverRequest @ angular.js:8025wrappedCallback @ angular.js:11498wrappedCallback @ angular.js:11498(anonymous function) @ angular.js:11584Scope.$eval @ angular.js:12608Scope.$digest @ angular.js:12420Scope.$apply @ angular.js:12712(anonymous function) @ angular.js:18980x.event.dispatch @ jquery-2.0.3.min.js:5y.handle @ jquery-2.0.3.min.js:5 services.js:35 error: undefined
另外,在调用时:
var url = 'http://muser:mpasswd@myredmine/redmine/issues.json&callback=JSON_CALLBACK'; $http.jsonp(url).success(function (data) { console.log('success'); }).error(function (error) { console.log('error:: ' + error); });
我犯了同样的错误
请考虑muser,mpasswd和myredmine就是例子.
解决方法
从
ngDocs:
The name of the callback should be the string JSON_CALLBACK
Angular将使用angular.callbacks_ {0-9a-z}在内部替换该字符串
所以首先将代码更改为:
var url = 'http://muser:mpasswd@myredmine/redmine/issues.json?callback=JSON_CALLBACK'; $http.jsonp(url).succe...
玩这个fiddle似乎Redmine剥去了点.从urls这样使angular.callbacks_0变为angularcallback_0,这是未定义的.
您可以在github阅读更多内容,但有一个问题.
可能的解决方案
1)另一个用户在SO here上发布了一个hack,用于将回调的名称更改为自定义回调.
根据@ Todi-Adiatmo的黑客工作fiddle.
2)根据对张贴在github这个问题找到@dancras另一种解决方案是与呼叫定义不确定angularcallbacks_ {..}到angular.callbacks_ {..},然后删除全局angularcallbacks_.
您必须在jsonp调用之前立即使用它:
var c = $window.angular.callbacks.counter.toString(36); $window['angularcallbacks_' + c] = function (data) { $window.angular.callbacks['_' + c](data); delete $window['angularcallbacks_' + c]; };