Tag Archives: JSON

Angularjs and Grails withFormat and json

I have been doing a mixed angularjs and grails project and ran into problems getting json to come back from the controller request with a withFormat block.

What I expected

I expected that it would call the grails app controller index method and with the withFormat to pick out that the request came is as a json request so return json. This is not the case, it would send me back the html page instead.

The problem was that grails would see */* as the accept headers and return just the html.

Grails code from the grails controller

def index() {
        def books = Book.findAll().collectEntries { book -> [book.title, book] }.values()
        withFormat {
            html books: books
            json { render books as JSON }
        }
    }

Angularjs json request that returns html

$http.get('/book/index').success(function(response) { };
}

Continue reading