Erik Zaadi

The tales of a half breed devops and web developer

jQuery Compatible JSONP With Nginx

| Comments

I got inspired by this awesome article by Gabriel Weinberg to hack a bit on nginx.

It’s a great article which I highly recommend to read.

The part that specifically interested me was turning JSON into JSONP compatible calls, usable both for proxying remote / local apis that doesn’t supply JSONP functionality and for simple to padd local static JSON files.

What bothered me though was the fact that the name of the method to pad into the JSON response was hard coded.

Here’s Gabriels code snippet:

Gabriel Weinbegs Code Snippetlink
1
2
3
4
5
location ^~ /ext_api3/ {
    echo_before_body 'parseResponse(;
    proxy_pass http://api.external.com/;
    echo_after_body ');';
}

When you use jQuery to do an ajax request, you add ?callback=? to your url, which will be replaced by a random function name, E.g: callback=jQuery123123. To achieve the same with nginx, I modified the snippet:

Modified to handle callback variable
1
2
3
4
5
6
7
8
location /json/ { #can be any location of course
    if ( $arg_callback ) {
        echo_before_body '$arg_callback(';
        echo_after_body ');';
    }
    #proxy or remote here
    try_files $uri $uri/ /index.html;
}

Now if we take a simple JSON file:

Sample JSON
1
2
3
4
{
    "aa" : "bb",
    "cc" : 123
}

And call nginx to fetch it via the location we configured in the snippet above, with the url http://server.com/json/sample.json?callback=Ahoy we’d get:

JSONP Result
1
2
3
4
Ahoy({
    "aa" : "bb",
    "cc" : 123
});

Enjoy

Comments