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) { };
}

Headers sent by the request 
Accept:application/json, text/plain, */*

Grails and Content Negotiation from the source. content negotiation

How to do a request against the controller and return json

You can do either via the UrlMapping configuration file or via the url param

Via UrlMapping

Grails 2.0 allows you to add the .format to the UrlMappings to allow negotiation via the url

"/$controller/$action?/$id?(.${format})?"{

Angularjs json request that returns json via format

You have to add the .json to the request url to get it to work correctly.

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

 

Via the url param

You can also do it via the url param format=json

Angularjs json request that returns json via url param

$http.get('/book/index.json?format=json').success(function(response) { };
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s