Skip to content Skip to sidebar Skip to footer

Angularjs $resource Calls The Wrong Api Url When Using Method:post

Not the easiest issue to put into a title. Anyhow, my app is built on nodejs/expressjsand has an API set up for the url: EDIT: The current code I'm using is: $scope.updateProduct =

Solution 1:

As you can see in ngResource docs, $resource receive 3 parameters:

$resource(url[, paramDefaults][, actions]);

You are passing your action as a parameter.

The correct version would be:

$scope.updateProduct = $resource('/api/updateProduct/:product/:param/:value',{}, {'save':{method:'POST'}});

Note that it isn't even necessary, because when you use $resource you already create the default methods:

{ 
    'get':    {method:'GET'},
    'save':   {method:'POST'},
    'query':  {method:'GET', isArray:true},
    'remove': {method:'DELETE'},
    'delete': {method:'DELETE'} 
};

Solution 2:

First of all, your have defined the save() to have a parameter called "brand", but in your url template and in the call to save(), you are using "product". I guess it's a typo.

You say when you are using browser to visit the url, it works well; but when angular is make a PUT request to the same url, nothing is happening. This indicates that your backend is configure to process only GET requests for this particular url pattern. Therefore, you need to make sure that your backend is accepting PUT requests.

Solution 3:

I was struggling with this issue and was able to pass parameters to the resource by doing the equivalent call below (notice the '$' before 'save').

$scope.updateProduct.$save({
    product : $scope.post._id, 
    param: 'likes', 
    value: $scope.user._id
});  

I also did not define a 'save' method in the resource. According to Angular docs:

"Calling these methods (meaning non-GET methods) invoke $http on the url template with the given method, params and headers. When the data is returned from the server then the object is an instance of the resource type and all of the non-GET methods are available with $ prefix. This allows you to easily support CRUD operations (create, read, update, delete) on server-side data."

Post a Comment for "Angularjs $resource Calls The Wrong Api Url When Using Method:post"