Cannot read property 'protocol' of undefined

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

Getting that error in console when trying to get data from a API. Anybody have this issue before?

var url = "https://api.website.com/get/?type=events&lat=" + localStorage.getItem('latitude') + "&lng=" + localStorage.getItem('longitude') + "&distance=50";  $http({     headers: {         'Content-type': 'application/json'     } })  $http.get(url).success(function (events) {     $scope.events = events; }); 

error:

TypeError: Cannot read property 'protocol' of undefined at Gb (http://localhost:38772/www/js/plugins/angular.min.js:114:238) at s (http://localhost:38772/www/js/plugins/angular.min.js:65:249) at new EventsController (http://localhost:38772/www/js/angular.js:4:5) at d (http://localhost:38772/www/js/plugins/angular.min.js:30:452) at Object.instantiate (http://localhost:38772/www/js/plugins/angular.min.js:31:80) at http://localhost:38772/www/js/plugins/angular.min.js:61:486 at http://localhost:38772/www/js/plugins/angular.min.js:49:14 at q (http://localhost:38772/www/js/plugins/angular.min.js:7:380) at E (http://localhost:38772/www/js/plugins/angular.min.js:48:382) at f (http://localhost:38772/www/js/plugins/angular.min.js:42:399)  

回答1:

You're issuing a malformed $http request.

You are not supposed to set your headers in a separate call to $http. Call to $http() will actually issue the request, but since you configured it with just the header (no url or method), it throws that error at you (as expected).

If you want to set your header you'll want to do that by passing a custom config object as a second parameter to your $http.get() call:

$http.get(url, {   headers: {     'Content-type': 'application/json'   } }).success(function (events) {   $scope.events = events; }); 


回答2:

This error occurs when something goes wrong in request, for ex. if you set url as undefined, invalid method, or invalid content type, anything wrong with request object will throw this error.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!