In the latest codebar.iotutorial, we are working with AJAX Requests. We have already used the Github and the BBC APIs issuing GET requests to retrieve information.
I built a sinatra app that handles JSON requests using POST, PUT and GET to manage a Hangman game. As part of doing this, I also had to enable CORS1 in Sinatra so that the calls could be executed from any domain.
To enable CORS first you must allow requests originating from any domain by setting the Access-Control-Allow-Origin to any (unless you only want to only allow specific domains).
For every not so simple request, a preflight request is also issued. The browser asks the server for permission to issue the request and waits until its granted before doing anything else.
The preflight request is OPTIONS. The response must have Access-Control-Allow-Origin and Access-Control-Allow-Methods defined. To allow requests issued by JQuery, I also had to allow the X-Requested-With header.
Using a database to store the game state is a bit overkill for such a simple app, so instead I store the state in a Base64 encoded token which the client sends on each request – thanks to @barisbalic for the suggestion. Alternatively, a cookie could have been used, but explicitly passing the token allows the client to run multiple games at the same time, and also required less effort to implement .
There is some missing functionality like the startup screen and the wind speed. I would also like to optionally automate one of the two player and store scores for a username. If you’d like to help out you can fork the project and issue a PR.