Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Basya Rosemann
Basya Rosemann
1,974 Points

HTTP PUT and POST to static JSON file return 404 error

I am trying to build a small AngularJS CRUD type application so I can learn the framework.

My data is stored in static .JSON files. I am using GRUNT to serve my application. (using npm command "grunt serve").

I have created the following two factories in my app.js file, so that I can pick up my data RESTfully using ngResource:

.factory('bookFactory', ['$resource', 
    function($resource) {
    return $resource('api/books/:bookId.json', {}, {
        update: { method: 'PUT', params: {bookId: '@bookId'}, isArray:false }
    })     
}])
.factory('booksFactory', ['$resource',
    function($resource) {
    return $resource('api/books/:bookId.json', {}, {
        create: { method: 'POST', params: {bookId: '@bookId'}, isArray:false },
        query: { method:'GET', params: {bookId:'books'}, isArray:true }
    })
}]) 

The QUERY action is working. I am able to query my books from my JSON file and display them in the browser. However, when I try to use the PUT or CREATE methods, I get a 404 NOT FOUND error...

The way I am calling the PUT action is as follows.

In my view, I have a link with the attribute:

ng-click="updateBook()"

In the controller linked to that view, I have the updateBook function:

$scope.updateBook = function () {
    bookFactory.update({bookId: $scope.book.id});
    $location.path('/book-list');
};

What is causing this problem? Is it possible to modify a JSON file stored locally on my computer if I serve the app through Grunt? If so, what's wrong with my code?

Thanks for your help!

2 Answers

Grunt serve is okey for send a GET request to your running process and getting the file content. BUT grunt serve never gonna writing into your the files on your hard drive.

Basya Rosemann
Basya Rosemann
1,974 Points

Hi Zoltan Radics - Thank you for your response!

Two questions:

  1. Why won't Grunt Serve write to files on my hard drive?
  2. How do I need to change my setup so that my files can be modified?

Thank you very much for your help!

Basya

  1. Grunt Serve is a development tool which handles GET requests to serves static files on your local computer. (to make it visible in a bowser for eg.)
  2. You have to write an API to handle the JSON file read / write actions.