2

I am trying to learn about REST server and hosting a flask server.

running curl on the server url i get:

HTTP/1.1 200 OK
Access-Control-Allow-Methods: POST, OPTIONS, GET, HEAD
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 21600
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Jun 2014 07:08:41 GMT
Server: gunicorn/19.0.0
Content-Length: 36
Connection: keep-alive

But when i try to access data from it from another url i get:

XMLHttpRequest cannot load --server url--. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin --page url-- is therefore not allowed access.

The following codes I have tried so far to get data:

  var formData = new FormData();
  formData.append("name",username );
  formData.append("id", userid);

  var request = new XMLHttpRequest();
  request.open("POST", "my-server-url");
  request.send(formData);
  console.log("Running Create user")
  console.log("Status: "+request.status);
  console.log("error: "+request.error);
  console.log("responseText: "+request.responseText);

Returns

Running Create user
Status: 0
error: undefined
responseText: 

I have tried with ajax and jquery which also fails with the same error described above

  $.ajax({  
            url:'--server url--',  
            type:'POST',
            data :  mydata,      
            dataType: 'JSON',
            success: function(data) { 
                  console.log(data)   
            }  
        }); 

also

  $.ajax({  
                url:'--server url--',  
                type:'POST',
                data :  mydata,      
                dataType: 'JSONP',
                async: false,
                success: function(data) { 
                      console.log(data)   
                }  
            }); 

I am using crossdomain decorator snippet in the python code.

For a sample of my server route handling:

@app.route("/",  methods=['POST', 'GET', 'OPTIONS'])
@crossdomain(origin='*')
def create():
    if request.method == 'POST':
        name = request.form['name']
        id = request.form['id']
        #duplicate = collection.find_one({'name': name, 'token': token})
        duplicate = collection.find_one({'id': id})
        if not duplicate:
            data = {'name': name,
                    'id': id}
            collection.insert(data, safe=True)
            response= make_response({'status': 'created'}, 201)
            response.headers['Access-Control-Allow-Origin'] = "*"
            return response 
        else:
            response= make_response({'status': 'already exists'}, 302)
            response.headers['Access-Control-Allow-Origin'] = "*"
            return response
Wasi
  • 1,473
  • 3
  • 16
  • 32
  • Do you see an OPTIONS request in your browser's console? If so, can you run curl -XOPTIONS on your server and post the result here? – kojo Jul 02 '14 at 10:28
  • @kojo Thanks for the response. I have finally found a workaround and solved the cors issue sending formData via ajax and setting `processData: false,contentType: false,` ( Now I'm trying to figure out why it is working :-) ) – Wasi Jul 03 '14 at 08:33

1 Answers1

0

I have finally managed to solve the problem, the following changes I have made to the ajax code

var formData = new FormData();
formData.append("id", userid); 
$.ajax({
            url: '--server--',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data){
              //do something with data
              console.log(data)
            },
            error: function(e) {
                    //handle error
                    console.log(e)
                  }


          })

I had to make this changes on the server too:

@app.route("/",  methods=['POST', 'GET', 'OPTIONS'])
@crossdomain(origin='*')
def create():
    if request.method == 'POST':
        name = request.form['name']
        id = request.form['id']
        #duplicate = collection.find_one({'name': name, 'token': token})
        duplicate = collection.find_one({'id': id})
        if not duplicate:
            data = {'name': name,
                    'id': id}
            collection.insert(data, safe=True)
            return jsonify({'status': 'created'}), 201
        else:
            return jsonify({'status': 'already exits'}), 302
Wasi
  • 1,473
  • 3
  • 16
  • 32
  • 2
    This way you got rid of CORS requirement altogether. It is not required if the type is POST and Content-Type is application/x-www-form-urlencoded (which it is in your new example) – kojo Jul 03 '14 at 11:20