jsonangularjsangular-resource

Angular resource 404 Not Found


I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.

I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:

app.factory('Product', function($resource) {
        return $resource('api/products.json', { id: '@id' });
});

My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:

var item = Product.query().$promise.then(function(promise) {
  console.log(promise) // successfully returns JSON objects
});

However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.

This is the error that I get:

http://localhost:3000/api/products.json/12-34 404 (Not Found)

I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?

Here is my data structure:

[
    {
        "id": "12-34",
        "name": "Greece",
        "path": "/images/athens.png",
        "description": ""
    },
    ...
]

Solution

  • By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.

    Then configure your $resource instance to use the proper verb like this :

    app.factory('Product', function($resource) {
            return $resource('api/products.json', { id: '@id' }, {'update': { method:'PUT' }});
    });
    

    check $resource docs for more info.


    NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db. Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.