I'm writing JavaScript and AngularJS code and i'm trying to get through a https website some JSON data.
My code :
var app = angular.module('myApp', []);
app.controller('DecisionsCtrl', function($scope, $http) {
$http.get('https://test3.diavgeia.gov.gr/luminapi/opendata/search.json?org=10599')
.success(function (response) {$scope.decisions = response.decisions;});
});
and
<tr ng-repeat="x in decisions | limitTo:10 ">
<td>{{x.protocolNumber }}</td>
<td>{{x.subject}}</td>
<td>{{x.extraFieldValues.financialYear}}</td>
<td>{{x.extraFieldValues.budgettype}}</td>
</tr>
</table>
A pic from error through firefox console :
If i use http website or if i download https stuff into file.json, there isn't any problem.
Could anyone help me?
Your request is being blocked by CORS: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
If you control the server, then you can add the 'Access-Control-Allow-Origin' header to allow the host you are attempting to access it from.
If you don't control the server, contact the administrators and ask them to add it, or they may have another method of access (such as JSONP).
Related
I need to use angularJS to call a rest api located at localhost:80/users.
The problem is that it does not read the url (the url works if I access it in the browser).
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("https://www.w3schools.com/angular/welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>
</body>
</html>
When I run the code from above (which is from https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_http) on my PC I don't see the correct result. Instead
Today's welcome message is:
Hello AngularJS Students
The $http service requests a page on the
server, and the response is set as the value of the "myWelcome"
variable.
I see
Today's welcome message is:
The $http service requests a page on the server, and the response is
set as the value of the "myWelcome" variable.
in Chrome and Firefox.
If I replace the url from the code (https://www.w3schools.com/angular/welcome.htm) with my localhost/users, I also don't see the correct result. But, if the url is https://restcountries.eu/rest/v1/region/europe it works! Why does it work for some URLs and it does not for others?
The server which is running the angularJs uses a different localhost port than the Rest server provider. Could this be the problem?
I use the latest AngularJS version (1.6.7).
The app I'm developing allows users to change the IP of the server (where the REST API is). This address is stored in a variable that can change, but the problem is that when the services are instantiated, the base URL cannot be changed. Following this answer I was able to change the url of some of the services, but I can't do the same for those who have POST actions.
I've tried several configurations, but there's always a problem. For example, this:
// Services file
app.factory('Bookings', BookingsFactory)
function BookingsFactory($resource, GlobalVariables) {
return $resource('http://:url/api/bookings/:id/', null, {url: '#url'});
}
//Controllers file
Bookings.save(booking, {url: GlobalVariables.IPServer});
Throws this error message "net::ERR_NAME_NOT_RESOLVED", because the request URL is not correct: "http://api/bookings/?end_time=2015-06-30T09:30&name=Reunion&room=1&start_time=2015-06-30T09:43&started=true".
If I call it like this:
//Services file
app.factory('Bookings', BookingsFactory)
function BookingsFactory($resource, GlobalVariables) {
return $resource('http://:url/api/bookings/:id/', {url: '#url'});
}
//Controllers file
Bookings.save({booking: booking, url: GlobalVariables.IPServer});
I get a 400 BAD REQUEST error, and the response asks for content for all the required fields: "This field is required."
I'm using AngularJS v1.3.13. Is there a way to change the base URL in every petition with this approach, even on POST requests? Or even better, is there a way to update the URL in every factory of the application after the app is started?
In an app that I work on I use the $rootScope to hold my base server URL for all requests. I don't know if that's a good way to use $rootScope or not, but what's for sure is that the app is working.
oops sorry I forgot to also add that I can change the base URL while the app is running, which is what you need.
I have an AngularJS application and I want to cache the REST service responses. I found some libraries like angular-cached-resource which can do this by storing the data into the local storage of the web browser.
But sometimes I do some POST / PUT / DELETE REST calls and then some of the REST previously cached service responses need to be performed again. So it seems that it is possible to delete the cached responses then and the call will be sent to the server next time.
But what about if the server sends me in HTTP Header some values like the expires or the etag? I have to read the HTTP Header and react by myself or is there a library in AngularJS which can also handle this?
So if I should hit the server and not read the cache of the local storage is dependent on the HTTP Header Cache fields and if there are any PUT / POST / DELETE calls which have the response that for example "reload of every user settings element" are needed. So I have to take this response and create a map which tells me that for example REST services A, C and F (user settings related stuff) needs to hit the server again next time when they are executed or if the Cache expires from the HTTP Headers.
Is this possible with an AngularJS library or do you have any other recommendations? I think this is similar to Observer or PubSub Pattern, isn't it?
One more thing: Is it also possible to have something like PubSub without using a cache / local storage (so also no HTTP Header Cache controls)? So I can not call the REST service, because then it would hit the server, which I do not want in some circumstances (response from a previous REST call which returns me the event "reload of every user settings element").
You can try something like this.
app.factory('requestService', ['$http', function ($http) {
var data = {};
var service = {
getCall : funtion(requstUrl, successCallback, failureCallback, getFromCache){
if(!getFromCache){
$http.get(requstUrl)
.success(function(data){
successCallback(data);
data.requstUrl = data;
})
.error(function(){
failureCallback(data);
})
}else{
successCallback(data.requstUrl);
}
},
postCall : function(requestUrl, paramToPass, successCallback, failureCallback, getFromCache){
if(!getFromCache){
$http.post(requestUrl, paramToPass)
.success(function(data){
successCallback(data);
data.requstUrl = data;
})
.error(function(data){
failureCallback(data);
})
}else{
successCallback(data.requstUrl);
}
}
};
return service;
}]);
This is just a simple code I wrote to implement your concept. I haven't tested it and is all yours.
I am trying to call a REST service using Angular 1.3 but keep getting an "Error: error:badcfg
Response does not match configured parameter".
I suspect it is in my controller where I call the $scope.data. I believe .data is correct but it is throwing this error.
Here is my service, including a test REST call:
var pfcServices = angular.module('pfcServices', ['ngResource'])
pfcServices.factory('pfcArticles', ['$resource',
function($resource){
return $resource('https://myrestcall.com/data, {}, {
query: {method:'GET'}
});
}]);
Here is my controller:
var pfcControllers = angular.module('pfcControllers', []);
pfcControllers.controller('pfcCtrl', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {
$scope.data = pfcArticles.query();
}]);
Within IE, I get a CORS message of: XMLHttpRequest for https://pfc.azure-mobile.net/tables/articles required Cross Origin Resource Sharing (CORS). This does not occur within Chrome.
However, I am not sure if this is related, or just a bad call on my part. I have added my test site to the CORS in Azure Mobile Webservices where I am hosting the test REST call.
I am newer to Angular, so I am leaning towards a bad call on my part.
I am not sure why have set query properties on the resource. Either remove the configuration for query
return $resource('https://pfc.azure-mobile.net/tables/articles', {});
or set isArray true on the query configuration.
return $resource('https://pfc.azure-mobile.net/tables/articles', {}, {
query: {method:'GET',isArray:true}
});
The error is coming because Angular is not able to deserialize your response as it expects an object but the response from the call is an array.
The query method on $resource already has this flag set, but since you are redefining the query configurations this error is occurring. Do check the $resource documentation.
I'm currently developing a web application using AngularJS on the fronted and NodeJS on the backend with express. I've had trouble requesting my backend API from the fronted however and hope you guys can help me.
Backend (NodeJS):
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
Frontend (AngularJS):
myApp.controller('myController', function($scope, $http) {
delete $httpProvider.defaults.headers.common["X-Requested-With"]
$http.get('http://localhost:5000/test').success(function(data) {
alert('Success')
}).error(function(data, status) {
alert('Error! ' + status + ' : ' + data)
})
})
When I refresh the app I get an alert saying: Error! 0 :, however, when I request the backend with curl or by the browser, I get the test dict back. The frontend seems to be able to access the backend though because I see it in my backend log that it's done a request and got something back, but firebug says that the response is empty, what should I do?
Thanks so much, let me know if you need more info from me.
Mattias
Make sure that your frontend and backend servers have the same origin (protocol, host and port). If not, then you does not recieve response since you make cross-origin ajax request. In this case you should send special header from your backend to allow it:
Access-Control-Allow-Origin: *
You can add response header with the following code:
res.set('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Origin', '*');
Use res.status(status).json(obj) instead of res.json(status, obj)