jquery - Accessing request.json in Flask results in an exception -
i'm using flask 0.10.1, , have flask function starts this:
@app.route('/logs', methods=['post']) def add_log(): db = get_db() print("\ninside /logs post\n===================") print(request.headers) print('--------------') print(request.form) print('--------------') try: print(request.json) except exception e: print('something real bad happened') print(e) if not request.json: print("abandon ship!") abort(400)
i'm making ajax request location via jquery:
$.ajax({ url: '/logs', contenttype: 'application/json', type: 'post', data: {'body': 'you know use body', 'tags': 'tagggssss'}, success: function(data) { console.log(data); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.tostring()); }.bind(this) });
it appears upon trying access request.json, flask functoin fails. here's flask server output:
inside /logs post =================== x-requested-with: xmlhttprequest accept-language: en-us,en;q=0.5 host: 127.0.0.1:5000 referer: http://127.0.0.1:5000/ connection: keep-alive content-type: application/json; charset=utf-8 pragma: no-cache content-length: 55 accept-encoding: gzip, deflate accept: */* user-agent: mozilla/5.0 (x11; linux x86_64; rv:28.0) gecko/20100101 firefox/28.0 cache-control: no-cache -------------- immutablemultidict([]) -------------- real bad happened 400: bad request 127.0.0.1 - - [11/apr/2014 13:16:30] "post /logs http/1.1" 400 -
the flask docs state:
if mimetype application/json [request.json, if understand correctly] contain parsed json data. otherwise none.
this leads me believe parsing json somehow failing, though i'm not sure how be. how can see problem is?
you not posting json; mimetype claims are. use json.stringify()
:
data: json.stringify({'body': 'you know use body', 'tags': 'tagggssss'}),
Comments
Post a Comment