我试图从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:
回调的名称应该是字符串JSON_CALLBACK
Angular将在内部用一个替换该字符串 angular.callbacks_{0-9a-z}
所以首先将代码更改为:
var url = 'http://muser:mpasswd@myredmine/redmine/issues.json?callback=JSON_CALLBACK'; $http.jsonp(url).succe...
玩这个小提琴似乎Redmine.
从网址中删除点,从而制作angular.callbacks_0
出angularcallback_0
未定义的点.
你可以在github上阅读更多内容,但有一个问题.
1)有其他人所发布用户对SO一劈这里给回调的名称更改为一个自定义.
工作拨弄根据@托迪,Adiatmo的黑客.
2)根据@dancras在github上发布的问题上发现的另一个解决方案是angularcallbacks_{..}
通过调用来定义undefined ,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]; };
根据@ danca的解决方案工作小提琴.