The following works fine, but I am thinking this modifies the $httpProvider globally, which isn't what I want.
angular.module('SessionService', ['ngResource'])
.config(function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
})
.factory('Login', function($resource){
var resource = $resource('/adminui/login',{},{
post:{
method:"POST",
isArray:false
},
});
return resource;
})
LoginCtrl = function($scope,Login) {
$scope.login = function(){
Login.post($.param({user:$scope.user.username,password:$scope.user.password}),$.noop,$.noop)
}
}
Is there anyway to do this instead?
...
.factory('Login', function($resource){
var resource = $resource('/adminui/login',{},{
post:{
method:"POST",
isArray:false,
headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'} // ignored
},
});
return resource;
})
The "headers" parameter seems to be ignored. the request is still
Content-Type:application/json;charset=UTF-8
Is my value for headers ok?
I have confirmed that 1.1.3 does indeed support this. However, you need to make sure you also get the 1.1.3 version of the resource service. A quick test of:
angular.module('myApp', ['ngResource']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {templateUrl: 'partials/partial1.html',controller: 'MyController'});
$routeProvider.otherwise({redirectTo: '/'});
}])
.controller("MyController", function( $scope, Bug) {
Bug.post({test:"test"});
})
.factory('Bug', function($resource){
var resource = $resource('/bug',{},{
post:{
method:"POST",
isArray:false,
headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
},
});
return resource;
});
This will make a request with the headers set to (confirmed using Chrome):
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
A quick note, I was unable to find a download of the angular-resource.js, so I had to go the the github website to download it. It is here.
For some giggles, I created a fiddle. Notice that there will be a failed POST call, but its headers are set correctly. Example Fiddle
While the development docs (as of 12 Oct) show that overriding headers is possible in a $resource, it hasn't yet been released (v1.0.2 or v1.1.0). The feature is in the v1.0.x and master branches, however. In order to get at that feature, you might consider building from the v1.0.x branch for now.
How to build: http://docs.angularjs.org/#H1_4
Alternatively, you could pull from the snapshot build: http://code.angularjs.org/snapshot/
Looks like this feature will be in the next release.
Just adding the link to the 1.1.5 resource files (and others): http://code.angularjs.org/1.1.5/
You can set the URL to match the version you are looking for.
e.g. 1.1.4: http://code.angularjs.org/1.1.4/
Related
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.
In looking at How to read response headers in angularjs?, I see answers that involve making an http/ajax request after the page loads then getting the response headers.
I have an angularJS app that needs to render the page (immediately when it loads, not after) using some JSON in a custom response header key that I've added on my python backend.
Is there non-hacky a way to do this? Or is the very attempt at rendering a web page using AngularJS to parse response headers a hack in itself?
My headers look like this (I'm trying to get myjson) :
Keep-Alive:timeout=1, max=100
myjson:{"key2": "value2", "key1": "value1"}
Server:Apache
I think this is what you are aiming for, using $http and ngRoute. Forgive me if I'm misunderstanding. It's just loading data about this question via SO's API. If you click Load Data, you'll see the headers from SO on that page..
var app = angular.module('plunker',['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
template: '<h1>Test 1</h1>',
controller: 'HomeCtrl'
}).
when('/loaddata', {
templateUrl: 'load_data.html',
controller: 'LoadDataCtrl',
resolve: {
stackQuestion: function($http){
// We must return something with a promise. $http already does that, so does $resource.
// See: https://docs.angularjs.org/api/ng/service/$q
return $http({
method: 'GET',
url: 'https://api.stackexchange.com/2.2/questions/37491743?order=desc&sort=activity&site=stackoverflow'
})
}
}
}).
otherwise({
redirectTo: '/home'
})
}
]);
Then, in your controller:
app.controller('LoadDataCtrl',function(stackQuestion,$scope){
// now our data is here
$scope.question = stackQuestion.data;
$scope.headers = stackQuestion.headers();
});
http://plnkr.co/edit/ylOfSNqPAqjdg9rYxsbb?p=preview
I'm having to inline all resources into one file and this includes all the data that my application uses. With a gulp process, I've been able to create a $cacheFactory with all the data:
angular.module('app').run('$cacheFactory', '$http', function($cacheFactory, $http){
var $httpDefaultCache = $cacheFactory.get('$http');
$httpDefaultCache.put('/data/names.json',{...});
$httpDefaultCache.put('/data/places.json',{...});
});
My understanding of how to access this instead of making a call externally (file) may be incorrect.
I thought that by setting $httpProvider.defaults.cache = true, that my request to the endpoints of above would use the default cache.
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.cache = true;
}]);
Instead I get an error of
https://.../data/names.json 404 (Not Found)
As if it is looking within the the client and not in angular's cache. The type is also an xhr.
data.load(names, '/data/names.json');
...
function load(broadcastName, url, force){
if(!isLoaded[broadcastName] && !force){
console.log('Loading name data from', url);
// Make the http GET request
http({
method: 'GET',
url: url,
cache: true
}).then(function success(response){
console.log("response: ", response)
...
})
Had to create a custom http request that perfectly imitates angular $http service. It is used in several other applications we have, so I know it works. Only thing that has been added for this implenation is cache:true.
I've looked at several other questions that were similar, but I am still not understanding how it is working. How does using http default cache work? And is there something I should be aware of that I may be glossing over?
I hope this makes sense.
There's no special term for $http cache like '$httpDefaultCache'. It works like you expect it to work. You set either $httpProvider.defaults.cache or cache request option to true, and the response is retrieved from $http cache, which is available by default as $cacheFactory.get('$http').
Cache is just key/value storage. If request URL doesn't match a key completely, cache won't be used.
Here's an example how it works:
$cacheFactory.get('$http').put('/foo', 'foo');
$http({ url: '/foo', cache: true })
.then(result => {
$scope.foo = result.data;
})
.catch(result => console.error(result))
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.
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...