Skip to content

Testing JSONP Without a Server

April 27, 2013

(Note: See this article for a better solution.)

This is a trick for testing javascript code that needs to contact a web service for its data, when you don’t want to use the live service during testing (or when the web service is not available).

  1. Create the example response in a file. Start the file with an HTTP header that includes content type, so that the code processing the response doesn’t choke on the data:
    HTTP/1.1 200
    Content-Type:  application/javascript
    myCallback({ "my json example response" : "yah!" });
    

    Notice that the JSON string is padded by a callback function. This is the expected format for JSONP, but “myCallback” should be replaced with the name of the callback function the caller is expecting.

  2. Now that the response is stored in a file (called response.json), set up a server for it:
    $ while [ 1 ] ; do nc -l 50000 < response.json ; done

    This starts netcat listening on port 50000. When it gets a connection it will send the contents of the file. Putting it in a loop allows it to repeat for multiple requests.

  3. Try it. Call the web service using curl, and it should echo back the file, sans header (add -v to the curl command to see the header included).
    $ curl localhost:50000
    myCallback({ "my json example response" : "yah!" });
  4. Now use the test server in javascript code. For example, in jQuery:
    function myCallback(data) {
        // Here I can handle the response
    }
     
    $.ajax({type: 'GET', url: 'http://localhost:50000', dataType: 'jsonp'});

    Once testing is done, replace the URL with the actual service.

Leave a Reply

Your email address will not be published. Required fields are marked *