I have a angularJS application with an api service defined as follows:
(function ()
{
'use strict';
angular
.module('myApp')
.factory('api', apiService);
/** @ngInject */
function apiService($resource)
{
var api = {};
// Base Url
api.baseUrl = 'http://localhost:37243/';
api.Auth = $resource(api.baseUrl + 'auth/:verb', {}, {
login: {
method: "POST",
params: {
verb: 'credentials'
}
},
logout: {
method: "GET",
params: { verb: 'logout' }
},
getSession: {
method: "GET",
params: { verb: 'session' }
}
});
return api;
}
})();
and I am executing the login method from an Auth service like this:
authService.login = function (user, success, error) {
var apiAuth = new api.Auth();
apiAuth.$login(user).then(
function (response) {
var loginData = response;
authService.getSession();
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
success(loginData);
}, function (response) {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
error(response);
});
};
The api call is working but it is passing the payload in the query string rather than a data payload. I guess I have $resource configured incorrectly but cannot work out why.
What is being sent:
http://localhost:37243/auth/credentials?password=Password1&username=admin
What I want to be sent:
POST http://localhost:37243/auth/credentials {password: 'Password1', username: 'admin'}
Any ideas?
I've worked out the problem...
The reason is because I'm instantiating the resource object Auth and then executing the method.
From the ngResource documentation, the method signatures for "non-GET" methods (like mine) are:
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
non-GET instance actions: instance.$action([parameters], [success], [error])
So I was running under the second circumstance where there is no postData parameter.
Changing my code to not instantiate the object, as follows, worked:
//the login function
authService.login = function(user, success, error) {
api.Auth.login(null, user).then(
function(response) {
var loginData = response;
authService.getSession();
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
success(loginData);
}, function(response) {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
error(response);
});
};
For more info see this SO answer (up-voted)