I have just started learning AngularJS yesterday and building a app for practise to display images that the user enter in the search bar.
My code so far
HTML
<body>
<div id="content" ng-app="FlickerApp" ng-controller="MainController">
<h3>Search images in real time!</h3>
<input type="text" ng-model="searchPic" />
<button class="btn btn-primary" ng-click="showPics()">Search</button>
<div id="flickerPics" >
<ul ng-repeat="ph in data.photo">
<li>
{{ ph.id }}
{{ response }}
<img src="https://farm{{ ph.farm }}.staticflickr.com/{{ ph.server}}/{{ ph.id}}_{{ph.secret}}.jpg"
style="width:304px;height:228px;">
</li>
</ul>
</div>
</div>
and JavaScript
angular.module("FlickerApp",[]).controller("MainController",
function($scope, $http){
$scope.showPics = function () {
$http.get("https://api.flickr.com/services/rest/? method=flickr.photos.search&api_key=[API_KEY_HERE]&tags=" +$scope.searchPic+ "&in_gallery=1&is_getty=1&per_page=5&format=json&nojsoncallback=1")
.success(function(data){
$scope.data = data.photos;
}).error(function(data, status){
$scope.response = data + status;
});
}
});
I have not entered the API key, the url works because i have tested it manually.
I am testing this on JSFiddle
//try this
$http.get("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[API_KEY_HERE]&tags=" +$scope.searchPic+ "&in_gallery=1&is_getty=1&per_page=5&format=json&nojsoncallback=1")
.then(function(result){
$scope.data = result.data;
}).error(function(data, status){
$scope.response = data + status;
});
}
I suggest you upgrade your AngularJS version. Seems you're using one of the older ones that sets the X-Requested-With
request header which isn't compatible with most CORS configurations.
There is however a work-around. Try this
$http.get('https://api.flickr.com/services/rest/', {
params: {
method: 'flickr.photos.search',
api_key: [API_KEY_HERE],
tags: $scope.searchPic,
in_gallery: 1,
is_getty: 1,
per_page: 5,
format: 'json',
nojsoncallback: 1
},
headers: {
'X-Requested-With': null
}
}).then(function(response) {
$scope.data = response.data.photos;
})
Even if you upgrade, I highly recommend keeping the params
config as above. You wouldn't need the header
config though.
I think you are not setting X-Requested-With header while requesting. This issue is due to CORS. Try to study CORS, it is very important thing while doing cross-domain requests.
Try to add headers in your request like following:
$http({
'url':'yourUrl',
'method':'get',
'headers': { 'X-Requested-With' :'XMLHttpRequest'}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.