3

I've got problem with sending POST request from jQuery to server created in Flask. In POSTMAN extension to Chrome everything seems to work fine - response is sent back to client. While sending request from java script I get "415 Unsupported Media Type" error. Python(3.4.x) flask server has function:

from flask import Flask, jsonify, render_template, request

@app.route('/checers/register', methods=['POST'])
def register():
    clientId = 1
    print ("new client id: {0}".format(clientId))
    ret = {"clientId" : clientId};
    return jsonify(ret)

like I said, from POSTMAN parameters:

Url: http://localhost:8080/checers/register; Header: Content-Type; Value: application/json; Blockquote

made POST request working fine. In java script application I've tried two approaches: First with XMLHttpRequest:

function register3() {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function ()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            alert(xmlhttp.responseText);
        }
    };
    xmlhttp.open("POST", "http://localhost:8080/checers/register", true);
    xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xmlhttp.send("");
}

and second with jQuery:

function register() {
    var arr = {a : "a"};
    $.ajax({
        url: "http://localhost:8080/checers/register",
        type: "POST",
        // The key needs to match your method's input parameter (case-sensitive).
        data: JSON.stringify(arr),
            contentType: "application/json; charset=utf-8",
        accept: 'application/json',
        dataType: "json",
        success: function(data){alert(data);},
        error: function(errMsg) {
            alert(errMsg);
        }
    });
}

Of course I've tried different variations proposed in Stack, nothing had worked. I'm new in Flask and JS and it's my second day struggling with that. I've Found some information about cross-domain call OPTIONS method issues in flask server, maybe this is the case? Someone was struggling with that recently?

shinoshiba
  • 31
  • 2
  • Have you checked the developer console for errors? I feel it looks like cross-domain error since you're posting to localhost:8080 which doesn't allow from chrome. id that is the case try to use Jsonp callbacks or CORS.jar – Nomesh DeSilva May 24 '15 at 14:30
  • Netbeans log: Failed to load resource: the server responded with a status of 415 (UNSUPPORTED MEDIA TYPE) (16:43:41:306 | error, network) at http://localhost:8080/checers/register; Which id is a case? – shinoshiba May 24 '15 at 14:47
  • http://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc – Nomesh DeSilva May 24 '15 at 15:19

0 Answers0