1

I have created a python flask web-server that as of now just needs to print the data it receives to the screen. I am using HTML/javascript to make a webpage with a button. When the button is pressed, the JS should send a HTTP post request to the python server using AJAX. I got the webpage and the server to connect (I know because i am receiving a 200 code rather than a 'no JSON object' error), but the server does not appear to receive the post request. Instead, it responds with HTTP 200 OPTIONS. What do i need to do to send the json object to the server?

here is the webserver:

from random import randint
import time
import datetime
import json
import decimal
from flask import Flask, jsonify, abort, request, make_response, url_for

app = Flask(__name__, static_url_path="")

#standard error handlers
@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Bad request'}), 400)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.route('/api/data', methods=['POST'])
def post_data():
    data = json.loads(request.data)        
    print data
    print 'here'

    return jsonify({'result': 'true'}), 201



if __name__ == '__main__':
    app.run(debug=True)

here is the simple webpage:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "http://localhost:5000/api/data",
        type: "POST",
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({apiKey: "23462"}),
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 
hunter
  • 13
  • 3
  • When I click on the JSON button, I get an alert with `0` and another with blank. What output are you expecting to see? – Robᵩ Apr 03 '16 at 03:12
  • Related: http://stackoverflow.com/questions/1099787/jquery-ajax-post-sending-options-as-request-method-in-firefox – Robᵩ Apr 03 '16 at 03:18

1 Answers1

2

This might help:

@app.route('/api/data', methods=['POST', 'OPTIONS'])
def post_data():
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
            'Access-Control-Max-Age': 1000,
            'Access-Control-Allow-Headers': 'origin, x-csrftoken, content-type, accept',
        }
        return '', 200, headers
    data = json.loads(request.data)
    print data
    print 'here'

    return jsonify({'result': 'true'}), 201
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • thank you, i knew it had something to do with those headers i just did not know how to implement it – hunter Apr 03 '16 at 13:55