I am trying to Post a json to my flask server, but the post request always fails. This is how I am doing it, any idea what is am doing wrong?
jQuery.ajax({
url:'/someLink',
method:'POST',
data:JSON.stringify({"sampleKey":"Value"}),
success:function(data){
console.log(data);
},
});
And my flask server looks something like
@app.route('/someLink', methods=['POST'])
def someFn():
sampleKey = str(request.form['sampleKey'])
I believe there is some data serializing issue, as the following request works
jQuery.post('/someLink',{"sampleKey":"Value"},function(data){console.log(data)});
jQuery's .ajax
accepts either a plain object, or a query string as parameters for data. It does not accept JSON encoded strings.
It sends the data as 'application/x-www-form-urlencoded; charset=UTF-8'
'application/x-www-form-urlencoded; charset=UTF-8'
by default, which means unless you explicitly override this like Ian suggested possible (and the server is expecting it) you should not pass a JSON encoded string.
You can resolve this easily by passing the object.
From the API
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Try
jQuery.ajax({
url:'/someLink',
method:'POST',
data:{"sampleKey":"Value"},
success:function(data){
console.log(data);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.