Django API request is empty using React - python

So I am using axios in order to send a JSON request to Django API.
axios({
method: 'post',
url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint,
data: (reqData)
});
Just before the axios call I can see the request:
Object {nvm: "", a: Array(1), b: Array(1), c: Array(1), d: Array(1)}
However, when it gets to Django:
class TargetClass(APIView):
def get(self, request):
Here request is empty:
(Pdb) request.data
<QueryDict: {}>
(Pdb) request.body
b''
def post(self):
pass
What am I doing wrong?
P.S. Tried to send the request with fetch as well:
fetch('http://127.0.0.1:8000/' + this.state.dataRequestEndPoint, {
method: 'POST',
body: reqData,
})
None of it works.

Here is the solution for the problem above. Apparently, axios needs to send parameters:
var reqData = this.state.requestParams
axios({
method: 'post',
url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint,
params: {
'a': reqData['a'],
'b': reqData['b']
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
});
However, I don't know how good this solution is security-wise.

Related

Python flask request returns undefined values

I want to pass array to Python Flask but I got empty result or b'undefined=&undefined=&undefined='. Here is my code
Javascript
var test = [1, 2, 3];
$.ajax({
url: '/table',
data : test,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
and Python code
app.route('/table', methods = ['POST'])
def table():
#print(request.values)
print(request.get_data())
return 'got this'
You need to use JSON to send back values that are arrays, objects, etc in javascript:
var test = [1, 2, 3];
$.ajax({
url: '/table',
data : {'payload':JSON.stringify(test)},
type: 'get',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
Then, in the app:
import json
#app.route('/table')
def table():
_result = json.loads(flask.request.args.get('payload'))
return 'got this'
Use JavaScript object and send as content as application/json.
var test = {'input_1': 1, 'input_2': 2, 'input_3': 3};
$.ajax({
url: '/table',
data : JSON.stringify(test),
contentType: 'application/json',
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
In your flask app, you don't need import json to load received data because you have sent content as application/json.
from flask import jsonify, request
#app.route('/table', methods = ['POST'])
def table():
_result = request.json # because you have sent data as content type as application/json
return jsonify(_result) # jsonify will response data as `application/json` header.
# {'input_1': 1, 'input_2': 2, 'input_3': 3}

Cant get desired response in react js from flask api

I am using the fetch library from reactjs for getting and pushing data to/from my flask API. But can't get the desired response from the my api.
This is my flask api:
#app.route('/adduser',methods=['POST'])
def indx():
data=request.get_json(force=True)
email=request.get_json()["email"]
password=request.get_json()['password']
try:
auth.create_user_with_email_and_password(email,password)
except:
userexists="User Already Exists"
try:
user=auth.sign_in_with_email_and_password(email,password)
id = auth.get_account_info(user['idToken'])
db.child("users").push(id)
except:
invalidCredentials="Wrong Credentials"
if request.get_json(force=True):
x={
"name":"sarmad",
"roll":"052"
}
s=json.dumps(x)
return s
else:
return ""
This is react js code:
fetch('http://127.0.0.1:5000/adduser', {
mode:'no-cors',
method: 'POST',
headers: {
'Accept': 'application/json',
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json'
},
body: JSON.stringify({
'email': this.state.email,
password: this.state.password,
name: this.state.name,
// userType: userTy,
dob:this.state.DOB,
address:this.state.Address,
gender:'male',
phone:'090078601',
// roles:roles
})
}).then((response) => response).then((responseJson) => {
console.log(responseJson);
//this.setState({pressed: false});
})
I need to receive the data passed back from the Flask API either as a string or json. This is my current response back:
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" _proto_: Response
Any help would be greatly appreciated!
Just do it with .json()
}).then((response) => response.json()).then((responseJson) => {
console.log(responseJson);
//this.setState({pressed: false});
})

Passing Dict of Arrays using Ajax and Django

I have a dictionary of arrays that I would like to pass to my Django view.
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:{
filter_dict: filter_dict,
},
success: function (data) {
console.log(filter_dict);
}
});
And in my view I would like to receive this dict:
if request.is_ajax():
filter_dict = request.GET.getlist('filter_dict')
print("Is Ajax", filter_dict)
But "Is Ajax []" gets printed out and just as an example, my filter_dict:
Designated Broker:["BMO"]
Fund Class:["OM"]
Any ideas why a blank array gets passed?
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:JSON.stringify({
filter_dict: filter_dict,
}),
success: function (data) {
console.log(filter_dict);
}
});
if request.is_ajax():
request_data = json.loads(request.GET)
filter_dict = request_data['filter_dict']
print("Is Ajax", filter_dict)

Unclear 404 get ajax error passing integer to django

Totally unclear 404 Ajax error.
var int_page_number = 2;
$.ajax({
type:'GET',
url: '/loadmore/',
data: { 'page_number' : int_page_number},
dataType: 'json',
success: function (data) {
alert(data);
}
});
In the place passing data, I tried both using apostrophe and not around page_number. It's 404 so error may be in frontedn, but anyways I attach django urls.py string just in case :
url(r'^loadmore/(?P<page_number>[0-9]+)/$', views.loadmore),
and views.py function, which is all right:
#api_view(['GET', ])
def loadmore(request,page_number):
answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date')
paginator = Paginator(answers_to_questions_objects,10)
current_page = (paginator.page_number)
answers = serializers.serialize('json', current_page)
data = {
'answers': answers
}
return Response(data)`
For your url you should make a call to the url like /loadmore/2/, but you make the call like /loadmore/?page_number=2. So your ajax should be like this:
var int_page_number = 2;
$.ajax({
type:'GET',
url: '/loadmore/' + int_page_number + '/',
success: function (data) {
alert(data);
}
});

Resource has no available deserialization method

Using Django I'm getting the following error when making a POST to my API:
The format indicated 'text/plain' had no available deserialization method. Please check your formats and content_types on your Serializer."
I have tried adding the enctype="application/x-www-form-urlencoded to the form but the error is the same. I'm thinking maybe this is a API serializer issues?
Any idea's?
This is the AJAX:
$.ajax({
url: '/api/v1/rewards/campaigns/',
type: 'POST',
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val());
},
data: $('#registration').serialize(),
success: function(data, textStatus) {
console.log('success');
},
error: function(errorThrown){
// data = JSON.parse(errorThrown.responseText);
console.log(errorThrown);
}
});
This is the resource it is posting to:
class urlencodeSerializer(Serializer):
formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencode']
content_types = {
'json': 'application/json',
'jsonp': 'text/javascript',
'xml': 'application/xml',
'yaml': 'text/yaml',
'html': 'text/html',
'plist': 'application/x-plist',
'urlencode': 'application/x-www-form-urlencoded',
}
def from_urlencode(self, data, options=None):
""" handles basic formencoded url posts """
qs = dict((k, v if len(v) > 1 else v[0] )
for k, v in urlparse.parse_qs(data).iteritems())
return qs
def to_urlencode(self, content):
pass
class CampaignCreateResource(ModelResource):
class Meta:
queryset = Campaign.objects.all()
resource_name = 'rewards/campaigns'
allowed_methods = ['post', 'get']
serializer = urlencodeSerializer()
validation = FormValidation(form_class=CampaignForm)
Add contentType: 'application/json; charset=UTF-8' to your $.ajax() call to indicate the content type of the request data.
dataType argument specifies the format of the response, not the request!

Categories

Resources