Flask-restful api post gives back empty body via javascript - javascript

Having a local database running via python, I'm trying to do some api requests to it via a website. First tried both GET's and POST's as python unittest, which worked fine.
Then using javascript; GET function working perfect but my POST function, whatever I do, sends over an empty body to the python function (variable data in python code) or in other words a dict with nothing in it, while I'm passing data through it.
relevant python snippet:
conn = sq3.connect("temp.db", check_same_thread=False)
class Login(Resource):
def post(self):
data = flask.request.form.to_dict()
lst = conn.execute(f"""SELECT AccountID, Role FROM Account
WHERE Email = \"{data['email']}\"
AND PassW = \"{data['passw_hashed']}\"
""").fetchall()
return {"LoginSucces": [{"AccountId": e[0], "Role": e[1]} for e in lst]}
app = flask.Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": '*'}})
api = Api(app)
api.add_resource(Login, "/login")
app.run(port=8080)
Javascript:
function req_login(){
let email_p = document.getElementById("login_email").value
let passw = document.getElementById("login_passw").value
let data = JSON.stringify({email: email_p,passw_hashed: passw.hashCode()});
const request = new XMLHttpRequest();
request.open("POST", IP+"/login");
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader('Content-Type', 'application/json');
request.send(data);
request.onload = (e) => {
let jsret = JSON.parse(request.response);
let topkey = Object.keys(jsret);
let data_arr = jsret[topkey];
alert(data_arr['AccountId']);
}
}
Tried with manual data in javascript as well to see if reading out the data was the problem, without succes with the following bit of code:
const data = `{email: "tst#gmail.com", passw: "testtest123"}`;
Where does it go wrong, what can I try/change. If you need any more info, send in comment

After quite a bit of debugging, I found the solution myself. Hope it helps someone:
replace data = flask.request.get_json()
with data = flask.request.json

Related

How can I get Text from Js to Python

<script>
function voice(){
var recognition = new webkitSpeechRecognition();
recognition.lang = "en-GB";
recognition.onresult = function(event){
console.log(event);
document.getElementById("speechto").value = event.results[0][0].transcript;
}
recognition.start();
}
</script>
I am making language translator web-app. And in above code, it takes input from the user using mic and print that in textarea in eng language. So I want this text in my python so that I can translate it and print it on another textarea. But i dont know how can I get that text from the js into my python code.
any soln?
Where is "your python"? I'm assuming this is on a browser over a network. You gotta set up a webserver (in python) to listen to network responses. Try webpy for a simple solution: https://webpy.org/.
You'll have to set up a URL endpoint to respond to POST requests. More info here: https://webpy.org/docs/0.3/tutorial#getpost.
And lastly, you'll have to set up your Javascript to send the post request and to use the response from your server to edit the textarea. You can use the JS fetch API to send the post request and handle the response from there.
Good luck hooking everything up
I assume you're using flask as that is tagged in your question. You need to establish a route to execute your python code and run your flask app which should listen to some TCP port on your computer (by default flask seems to use port 5000).
Then on your js code you can use the fetch method to send the text to that port. For example:
fetch('http://locahost:5000/{your flask route goes here}', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: {text you want to send goes here},
})
rather than using python just to do a translation, why not to use a simple javascript translate function?
var translate = async (t,src,dst) => {
var tt = new Promise(function(resolve) {
var i=0, len=0, r='', tt='';
const url = 'https://clients5.google.com/translate_a/';
var params = 'single?dj=1&dt=t&dt=sp&dt=ld&dt=bd&client=dict-chrome-ex&sl='+src+'&tl='+dst+'&q='+t;
var xmlHttp = new XMLHttpRequest();
var response;
xmlHttp.onreadystatechange = function(event) {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
response = JSON.parse(xmlHttp.responseText);
for (var i = 0, len = response.sentences?.length; i < len; i++) {
var r=(((response.sentences[i].trans).replace('}/g','')).replace(')/g','')).replace('\%20/g', ' ');
r=((r.replace('}','')).replace(')','')).replace('\%20/g', ' ');
tt += r;
}
if (tt.includes('}'||')'||'%20')) {
tt=((tt.replace('}/g','')).replace(')/g','')).replace('\%20/g', ' ');
}
resolve(tt);
}
}
xmlHttp.open('GET', url+params, true);
xmlHttp.send(null);
xmlHttp.onreadystatechange();
});
return await tt;
}

How do I get a specific key value from JSON object

This is my first time using any kind of APIs, and I'm just starting out in JS. I want to get the status of a server within a server hosting panel, to do this I need to log in (API/Core/Login), get a the value of a key called sessionID, then send that value to /API/Core/GetUpdates to get a response. When trying to pass the sessionID to GetUpdates, it sends undefined instead of the sessionID, I'm guessing I'm doing something wrong when trying to reference the key value. Here's my code:
var loginurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/Login";
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", loginurl);
loginRequest.setRequestHeader("Accept", "text/javascript");
loginRequest.setRequestHeader("Content-Type", "application/json");
loginRequest.onreadystatechange = function() {
if (loginRequest.readyState === 4) {
console.log(loginRequest.status);
console.log(loginRequest.responseText);
}
};
var logindata = '{"username":"API", "password":"password", "token":"", "rememberMe":"true"}';
loginRequest.send(logindata);
var statusurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/GetUpdates";
var statusreq = new XMLHttpRequest();
statusreq.open("POST", statusurl);
statusreq.setRequestHeader("Accept", "text/javascript");
statusreq.setRequestHeader("Content-Type", "application/json");
statusreq.onreadystatechange = function() {
if (statusreq.readyState === 4) {
console.log(statusreq.status);
console.log(statusreq.responseText);
}
};
var statusdata = `{"SESSIONID":"${loginRequest.responseText.sessionID}"}`; // Line I'm having problems with
statusreq.send(statusdata);
console.log(loginRequest.responseText.sessionID)
Here's the response of /API/Core/Login
{"success":true,"permissions":[],"sessionID":"1d212b7a-a54d-4e91-abde-9e1f7b0e03f2","rememberMeToken":"5df7cf99-15f5-4e01-b804-6e33a65bd6d8","userInfo":{"ID":"034f33ba-3bca-47c7-922a-7a0e7bebd3fd","Username":"API","IsTwoFactorEnabled":false,"Disabled":false,"LastLogin":"\/Date(1639944571884)\/","GravatarHash":"8a5da52ed126447d359e70c05721a8aa","IsLDAPUser":false},"result":10}
Any help would be greatly appreciated, I've been stuck on this for awhile.
responseText is the text representation of the JSON response.
Either use JSON.parse(logindata.responseText) to get the JSON data or use logindata.responseJSON

csrf_token verification with Javascript XMLHttpRequest() (403 Forbidden)

i am trying to send a XMLHttpRequest() post request to the Django Server but it shows 403 Forbidden,
after searching i found that it is due to CSRF verification , after seeing lot of similar content still i am unable to figure out how to implement csrf in XMLHttpRequest
i am including the js snippet that i am using
document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('click',event => {
if (event.target.id === "add-cart-button")
{ event.preventDefault();
const add_cart_button_id = event.target.dataset.pid
const item_class = event.target.dataset.type
const item_name = event.target.dataset.item
const size_chooser = `#${item_class}-size-${add_cart_button_id}`
var sel = document.querySelector(size_chooser)
const size = sel.value
const quantity_chooser = `#${item_class}-quantity-${add_cart_button_id}`
const quantity = document.querySelector(quantity_chooser).value
var request = new XMLHttpRequest()
request.open('POST','/addcart')
request.onload = () => {
const data = request.responseText
}
var data = new FormData()
data.append('iten_class',item_class)
data.append('item_name',item_name)
data.append('size',size)
data.append('quantity',quantity)
request.send(data)
}
})
})
i am sending this request to /addcart route of django server
def addcart(request):
return JsonResponse({'status':True})
which just returns this status
can anyone help me in csrf verification

xmlHttpRequest stuck on readystate 1

I'm working on my first XMLHttpRequest and am not having much luck. I think the error is somewhere on the flask side because at the request.onload line, the request readystate is 1, so it skips straight to request.send().
Javascript:
// Load user's last page
loadPage('chat');
window.onpopstate = e => {
const data = e.state;
document.title = data.title;
document.querySelector('#body').innerHTML = data.text;
};
function loadPage(name) {
const request = new XMLHttpRequest();
request.open('GET', '/{name}');
request.onload = () => {
const response = request.responseText;
document.querySelector('#body').innerHTML = response;
document.title = name;
};
request.send();
};
And on the Flask side:
import requests
from flask import Flask, jsonify, render_template, request, session
#app.route('/chat', methods=['GET'])
def chat():
channel = session['channel']
print('channel: ', channel)
return jsonify ({'channel': channel, 'username': session['username']})
Also of note: After the GET request is made, 'channel' isn't printing on the server side, which tells me the GET request is just not actually being made. Any idea on what's holding me up here?
This '/{name}' is not correct string interpolation syntax. It is evaluated literally as /{name}. I would have done '/' + name, but curiosity got the better of me and found the accepted answer to this question shows the correct syntax.

Sending Ajax request but not able to receive at the receiver's end

I am using XMLHTTPRequest object to send some data from one of the templates in Django to another function in view.py
This is a part of my template:
function fun_submit()
{
var var_theme = document.getElementById("theme").value;
var var_author = document.getElementById("author").value;
var var_entry = document.getElementById("entry").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET',"http://127.0.0.1:8000/first_page/something/",true);
var data_upload = var_theme;
xmlhttp.send('w='+encodeURI(var_theme));
window.location.href = 'http://127.0.0.1:8000/first_page/something/';
xmlhttp.close();
}
and my view function is:
def something(request):
py_data = request.GET.get('w')
return HttpResponse(py_data)
when I return py_data, the page says None. I suspect the data is not getting transmitted.
I don't want to implement AJAX using JQuery.
Any help or suggestion is really welcome. Thanks.

Categories