Search code examples
angularjsresthttpngresource

AngularJS $resource request, withCredentials with username and password


I'm trying to do a small application that should fetch json data from a homepage with basic http authentication.

This is my service:

app.factory('MySrvs', ['$resource', function ($resource) {

    return $resource("http://address/to/json/document");

}]);

This is my controller:

app.controller('MyCtrl', ['$scope', 'MySrcvs', 'Base64',
function($scope, MySrvs, Base64) 
var stuff =  MySrvs.query(function(data){
   console.log(data)
   $scope.mylist = data;
});

This works good for my mirrored page without auth.

However, the production should go to a page that needs withCredentials:true with username and password to set up. Where should this be added? I have access to a Base64 encoder.

Gratefull for any help.


Solution

  • The $resource configuration object is very similar to the $http configuration object (with a few changes). The value of the object, the action, is the name of the method on the resource object

    for example

    angular.module('myApp', ['ngResource'])
        .factory('UserService', [
            '$resource', function($resource) {
                return $resource('/api/users/:id', {
                    id: '@'
                }, {
                    query: {
                        method: 'PUT', // or something else 
                        headers:{'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='} 
                    }
                });
            }]);