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?