Flask not getting any data from jQuery request data

Viewed 14690

I've a handler for a URL,

@app.route("/", methods=['POST'])
@crossdomain(origin='*')
def hello():
    ss=str(request.data)
    print ss
    return ss

The handler cannot retrive the data part of the request. When using jQuery:

jQuery.ajax(
   {
      type: "POST",
      dataType: "json",
      data:"adasdasd",
      url: 'http://127.0.0.1:5000/',
      complete: function(xhr, statusText)
      {  alert(xhr.responseText) }})

nothing is returned

4 Answers

This worked for me.

In Javascript:

$.ajax({
  type: 'POST',
  url: "enter your correct url",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({title: 'My Title', article: 'My article'}),
  success: function(result){
    console.log(result)
  }
});

In Python (flask):

 from flask import request
 import json

 @app.route("/", methods=['POST'])
 def home():
   json_data = json.loads(request.data)
   print(json_data)
   return json_data

NOTE: The points are;

  • JSON.stringify()
  • contentType: "application/json; charset=utf-8"
  • json.loads
  • request.data
Related