Go into object with AngularJS - angularjs

I have trouble with my JSON-Files. I have an old one that works fine.
Now i get a new and i didn't find the way into the first "main_themes"-Object.
This is my actual module:
angular.module('destinationsApp', [])
.controller('destinationsCtrl', function($scope, $http){
$http.get('https://raw.githubusercontent.com/MAHUKI-Webdesign/suntrips.github.io/master/data.json').then(function(itemsResponse) {
$scope.items = itemsResponse.data;
});
});
Actually i make it with something like this:
<li ng-repeat="item in items">{{item.name}}</li>
How i have to do it?
Here's my Plunkr with the working version:
https://embed.plnkr.co/U4WHAFQRZ2JsUOJVlAu7/
Here's my Plunkr with the not working version:
https://embed.plnkr.co/b3OtRKgzp1OQ0h1L3jDA/

var url = "http://raw.githubusercontent.com/MAHUKI-Webdesign/suntrips.github.io/master/data.json";
$http({
method: 'JSONP',
url: url
}).
success(function(status) {
$scope.items = itemsResponse.data;
// handle valid reponse
}).
error(function(status) {
//your code when fails
});
You are getting 'Access-Control-Allow-Origin' header is present on the requested resource. Origin to solve this change the rest api to give access to the localhost.Also see this .. Use JSONP

since the response is an object just access the main_themes property.
$scope.items = itemsResponse.data.main_themes

Access the main_themes
$scope.items = itemsResponse.data.main_themes

Here's my Plunkr with the working version:
https://embed.plnkr.co/U4WHAFQRZ2JsUOJVlAu7/
Here's my Plunkr with the not working version:
https://embed.plnkr.co/b3OtRKgzp1OQ0h1L3jDA/

It does not work on Plunker;
Error that I got:
Mixed Content: The page at 'https://plnkr.co/edit/b3OtRKgzp1OQ0h1L3jDA?p=preview' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www2.suntrips.de/import/main_sub_themes-main.json'. This request has been blocked; the content must be served over HTTPS
Please make requests to server using HTTPS protocol when using Plunker.

Related

Angular http.get + WebApi = Cors failure

on server side I have a C# web api including a controller attributed like this on class level:
[EnableCors(origins: "http://localhost:51664,http://localhost,...", headers: "*", methods: "*")]
I can make ajax calls, e.g. form localhost just fine.
Now I am starting with AngularJS and the http.get-method fails with the following message:
XMLHttpRequest cannot load http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my AngularJS code:
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function($scope, $http) {
var onSuccess = function(data, status, headers, config) {
$scope.data = data;
};
var onError = function(data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get("http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40");
promise.success(onSuccess);
promise.error(onError);
});
</script>
In Fiddler, I can see, that the header of the AngularJS-HTTP-Get request has an "Origin: null" entry, which seems to be related to the problem. I think, if instead "null" the value would be "http://localhost", it should work.
Can anyone help me out?
Thank you!
Could it be because in your [EnableCors] attribute, you need to change headers: "", methods: "" to headers: "*", methods: "*"?
Also, you should not include a forward slash at the end of the origins url (if you did).
We had the same issue in our project and we tried so many options as per the suggestions from various web sites. But the thing that worked/working in our case is writing custom CORS provider as mentioned here.
Upppps!
When running in the fresh air today I suddenly was aware why Origin was null. It was, because I was not calling the web site in IIS, but instead I opened the file directly in the file system. For sure, there was no valid URL when doing so, and the Origin was null for the web server.

Getting error when trying get JSON from remote url

I'm trying load this json file from remote url. In the beginning I was using $http.get function, but I was getting the next error message:
CORS 'Access-Control-Allow-Origin'
Now I am using JSONP, but nothing happens.
service.js file:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http){
return $http({
method: 'JSONP',
url: 'http://vagalumewifi.com.br/timeline.json'
}).success(function(response){
return response.data;
}).error(function(err){
return err;
});
}]);
controller.js file:
angular.module("elcomaApp", []).controller('MainController', ['$scope', 'ElcomaService', function($scope, ElcomaService){
$scope.name = 'Natanael Santos';
console.log($scope.name);
ElcomaService.success(function(data){
$scope.elcomaData = JSON.parse(data);
var i = 0;
for (x in $scope.elcomaData){
console.log(i);
i++;
console.log(x.date);
}
}).error(function(data){
console.log(data);
});
}]);
app.js file:
var app = angular.module("elcomaApp", ['ngMaterial', 'ngRoute']);
I already hava read a lot of articles on stackoverflow, but no one work for me.
I'd suggest using $http.jsonp(url) method:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http) {
$http.jsonp('http://vagalumewifi.com.br/timeline.json')
.success(function(data) {
console.log(data); // you can't `return` here...
}).error(function(err){
console.err(err);
});
}]);
Note: be warned that you can't expect that return in an async method has the same behavior as in a sync environment... :-)
Your original error is your clue. The endpoint server won't allow access from another domain.
CORS: Cross Origin Requests
You need to allow access on the endpoint server for the type of HTTP method you want to use (i.e. GET, POST, HEAD, ...) Additionally depending on what you're doing you may need to allow for an OPTIONS request, see Preflighted Requests in the MDN documentation above.
If you don't have access to that server you may need to do a work around by making $http call a script on your server that will fetch the file for you. I've done this before using PHP as a proxy and using PHP's file_get_contents function to grab files from other servers of a different domain.

$http.get success method not called

I am new to AngularJS & NodeJS. I am trying to get a API response from NodeJS and display it in angular. I am using $http to make API call. Below is my nodeJS code.
var express = require('express');
var app = express();
app.get('/employees',function(req,res)
{
console.log("Test Output :");
res.status(200).send('Hello User');
});
app.listen(8080);
Below is my angular code
var myapp = angular.module('myapp',[]).controller('myappController', ['$scope','$http',function ($scope,$http){
$http.get('http://127.0.0.1:8080/employees')
.then(function(response)
{
window.alert("Success");
$scope.emdata=response.data;
},function(errorresponse)
{
window.alert("Error");
$scope.emdata=errorresponse.status;
});
}]);
I am using expression {{emdata}} in HTML page. When I open the HTML page I can see the console output "Test Output " in NodeJS terminal which means the API is getting called but I dont see "Hello User" in HTML page. It looks like the success function in $http.get is not getting called and only the error function is getting called. So I see an alert window with "Error" whenever I open the HTML page and response status as -1 in the place of {{emdata}}.
When I tried making the API call using Postman I get correct response with status 200. So I am wondering what is wrong?
Check headers, i.e. what format is accepted by $http request and the format of the response (JSON, plain text, etc).
Fix value in
$httpProvider.defaults.headers.common
or set needed one in
$httpProvider.defaults.headers.get = { ... };
or just use
var requestParams = {
method: 'GET',
url: '...',
headers: {
...
}
};
$http(requestParams).then(...);
Take a look at Setting HTTP Headers in official manual for more details.

API-key header is not sent (or recognized). Angularjs

I'm trying to access an API with AngularJS but I get the following error:
XMLHttpRequest cannot load http://www.football-data.org/alpha/soccerseasons/398/leagueTable?callback=JSON_CALLBACK. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://purepremier.com' is therefore not allowed access.
This is my code for the service:
angular.module('PremierLeagueApp.services', []).
factory('footballdataAPIservice', function($http) {
var footballdataAPI = {};
footballdataAPI.getTeams = function() {
$http.defaults.headers.common['Auth-Token'] = 'token';
return $http.get('http://www.football-data.org/alpha/soccerseasons/398/leagueTable?callback=JSON_CALLBACK');
};
return footballdataAPI;
});
I use an authentication token (api key) to access the api, but according the API owner this API key header is not sent or recognized. Do you have any idea how I can adapt the code to make this work? thanks!
You should hide that API key before posting on a public site such as this. I would advise you regenerate your key (if possible) just in case - better safe than sorry.
Assuming your site url is 'http://purepremier.com' from the error message, the API should add a 'Access-Control-Allow-Origin' header with your site URL to allow you access. Have a look here for more information.
This is not directly related to your problem, but I notice you are setting $http defaults every time getTeams() is called. You should either set this outside of the actual function call (preferably in a run block), or just send the GET request with that header specifically applied. As the API key is specific (I assume) to that call, you may not want to be sending it to anyone and everyone, every time you make a HTTP request.
Change your factory code like this:
factory('footballdataAPIservice', function($http) {
return {
getTeams: function(){
return $http({
url:'http://www.football-data.org/alpha/soccerseasons/398/leagueTable',
headers: { 'X-Auth-Token': 'your_token' },
method: 'GET'
}).success(function(data){
return data;
});
}
}
});
Inject factory in your controller and retreive the data:
.controller('someController',function(footballdataAPIservice,$scope){
footballdataAPIservice.getTeams().then(function(data){
$scope.teams=data;
console.log($scope.teams)
});
});
Here is the working plunker
You change the Auth-Token To Authorization
$http.defaults.headers.common['Authorization'] = 'token';
Because token is send via headers using Authorization
try jsonp
angular.module('PremierLeagueApp.services', []).
factory('footballdataAPIservice', function($http) {
var footballdataAPI = {};
footballdataAPI.getTeams = function() {
$http.defaults.headers.common['Auth-Token'] = 'token';
return $http.jsonp('http://www.football-data.org/alpha/soccerseasons/398/leagueTable?callback=JSON_CALLBACK');
};
return footballdataAPI;
});

Angular $http request issue

i am trying to retreive some images from a flickr service this one.
Unfortunately, i have the following error:
XMLHttpRequest cannot load http://api.flickr.com/services/feeds/photos_public.gne?format=json.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
Here's my code:
angular.module('myApp')
.service('getFlickrImages', function($http){
this.getData = function() {
delete $http.defaults.headers.common['X-Requested-With'];
return $http({
method: 'GET',
url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json'
});
}
});
angular.module('myApp')
.controller('MainCtrl', function ($scope, getFlickrImages) {
$scope.data = null;
getFlickrImages.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Here's a Plunker if someone can help me
I finally found that chrome plugin:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-ntp-icon
Install it, activate it and refresh the view.
It will a least let you work without that Access-Control-Allow-Origin issue.
It would be good if someone bring the fix but directly in the code...

Resources