The marked duplicate does show a workaround, but still doesn't answer why the $.post()
method is sending the wrong data type!
I have no reason to believe that the flask application is written incorrectly, but I will post details here for completeness.
I have an event that I wish to trigger a post request and receive the response from a flask server. The post request is as follows:
$.post(
"data_names",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data){
console.log(data);
}
);
Of course, the object that I'm sending and reading at this point is just dummy data.
On my flask server, I have a view set up that simply displays the
@app.route('/data_names', methods=['POST'])
def data_names():
logger.debug('data names post: {}'.format(flask.request.json))
print('method: {}\n\nheaders: {}\n\ndata: {}'.format(flask.request.method, flask.request.headers, flask.request.data))
return_obj = {'my_response': 4}
return flask.jsonify(return_obj)
For the 'data' field of the $.post
, I have tried to use stringify and a few other functions that I thought might work. My server will print this to the console in ALL cases:
DEBUG:__main__:data names post: None
127.0.0.1 - - [06/Nov/2016 08:57:15] "POST /data_names HTTP/1.1" 200 150 0.004000
method: POST
headers: Host: 127.0.0.1:5000
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://127.0.0.1:5000/analysis
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
Origin: http://127.0.0.1:5000
Content-Length: 30
Cookie: session=.eJwlzj0KwzAMQOG7aA7Flm1ZytSbBP_ItENIseOhlN69gY5v-OB9YGtdxwPWs09dYHtWWEGLeLKImkrwAQU5Wo_Ikg3Fq6OQJDY-sAmYChZi8eFSNUdHZGvmaKJgU_TGEqnWyzmXi2uVkjZjLTduhskl8dbXmENLEjE0x6HCAnNo_8-UOc5j136frzre41aOHb4_OpE0lg.CwDEmg.IqdOKaGiAGZwkkQzttLseUM2AxQ
Connection: keep-alive
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Accept: application/json, text/javascript, */*; q=0.01
Dnt: 1
data: b''
Additionally, my console will display the returned {my_response: 4}
This tells me that the POST is getting through, but that the data is not. It also appears to me that the data type that the post request is sending should be application/json
and not application/x-www-form-urlencoded
, but the documentation for $.post()
says that it can take a plain JSON object.
Thank you for your assistance,