So I’m trying to use the JavaScript Fetch API with Flask to get a string and Fetch successfully reaches Flask with no issues, but can’t get a text response from Flask. Here is my code:
Javascript:
fetch("/validatelogin", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({"username": credentials[0],"password": credentials[1]}, null, 4)
})
.then(res => Response.body)
.then(body => console.log(body))
and the python:
@app.route('/validatelogin', methods=['POST'])
def login():
users = loads(post(
'http://localhost:8000/sql',
headers=headers,
auth=HTTPBasicAuth('nonono','rnoonononoo'),
data=f"SELECT * FROM user WHERE username = {request.json['username']} AND password = {request.json['password']}"
).text)[0]["result"]
if users != []:
response = make_response("yes", 200)
response.mimetype = "text/plain"
return response
response = make_response("no", 200)
response.mimetype = "text/plain"
return response
Im trying to get a text response from flask using js fetch. I tried changing mimetype, changing status code, and using XHR but all it does is return undefined
sorry if the answer is simple or something because i’m really new to javascript and python.
2
Answers
I have found the answer thanks to this medium article. It seems that using
Response.Body
was what made it break. Instead you should useResponse.text
to get the texthere is my updated code
and i didn't do anything for the python code
.then(res => res.text).then(data => console.log(data);