Testing JSONP Without a Server
(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).
- 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.
- 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.
- 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!" });
- 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.
Trackbacks