Search code examples
jquerycorssinatraflask-restfulflask-cors

CORs request with flask api - Jquery POST request results in OPTIONs


I have a flask API to control an immersion heater device.

https://github.com/timcknowles/anovapi_backend/blob/master/anova.py

This is on my localhost server and it responds correctly to JQuery POST requests on the same domain e.g.

$(document).ready(function() {
            $("#start").click(function() {

                    $.ajax({
                      type: 'post',
                      url: 'http://192.168.0.13:5000/start',
                      dataType: 'jsonp',
                      success: function(data) {
                         $("#message").html(data);
                      }


$("#settemp").click(function() {

                    $.ajax({
                      type: 'post',
                      contentType: 'application/json',
                      url: ' http://192.168.0.13:5000/temp',
                      data: JSON. stringify ({"temp":"50"}),
                      dataType: 'json',
                      success: function(data) {
                         $("#message").html(data);
                      }
            });

However I wanted to build a sinatra client app on a different server

https://github.com/timcknowles/anovapi_frontend/blob/master/main.rb

to interact with the same api. The jquery is identical and works fine for the START call however for the TEMP call it doesn't work

In the developer console of firefox I can see it has OPTIONS instead of a POST request (response 200).

Initially I had cross domain problems with all my api jQuery requests and I thought I had resolved these by adding the flask cors extension to my api.

https://pypi.python.org/pypi/Flask-Cors

I don't understand why the temp call isn't working but the others are. I suspect it is because I am sending data in the form of temperature values.

Any advice hugely appreciated.


Solution

  • I think you need to initialize CORS() for Flask to work.

    Try putting this on line 12 of your python server:

    cors = CORS(app, resources={r"/*": {"origins": "*"}})
    

    You might also get away with just CORS(app) (I've never used Flask so I'm unsure).

    See the Flask docs under Simple Usage for more information.