birdy
birdy

Reputation: 9646

withFormat closure is not sending response based on ACCEPT header

I'm trying the withFormat closure in grails. I've got the following in my action:

    if (myInstance.save(flush: true)) {
            withFormat {
                html {redirect(action: "list") }
                js {render "alert('came here')"}
            }

    }

As I understand the withFormat closure: If the ACCEPT header is text/javascript then it will only render the alert and if it is ['text/html','application/xhtml+xml'] then it will redirect to list action. However, in my case it is always rendering the list action.

I'm using REST Console in Chrome and here are the details of my request header:

Accept: text/javascript
Content-Type: application/json
Connection: keep-alive
Origin: chrome-extension: //rest-console-id
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31

And here are the response headers:

Status Code: 200
Date: Fri, 10 May 2013 14:45:18 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Content-Language: en-US
Content-Type: text/html;charset=UTF-8

The response body is always coming back as HTML whereas I'm expecting JS

The mime types also seem correct in config.groovy

grails.mime.types = [
    all:           '*/*',
    atom:          'application/atom+xml',
    css:           'text/css',
    csv:           'text/csv',
    form:          'application/x-www-form-urlencoded',
    html:          ['text/html','application/xhtml+xml'],
    js:            'text/javascript',
    json:          ['application/json', 'text/json'],
    multipartForm: 'multipart/form-data',
    rss:           'application/rss+xml',
    text:          'text/plain',
    xml:           ['text/xml', 'application/xml']
]

What am I doing wrong here??

After some testing I found out that whichever closure comes first is taking precedence. If i have:

        withFormat {
            js {render "alert('came here')"}
            html {redirect(action: "list") }
        }

then always the JS is being rendered even if I an testing the application from browser...

Upvotes: 1

Views: 816

Answers (1)

dmahapatro
dmahapatro

Reputation: 50265

grails.mime.use.accept.header = true setting is required in Config.groovy. Do you have this set?

Refer the bottom of withFormat page.

Upvotes: 1

Related Questions