skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have found the answer thanks to this medium article. It seems that using Response.Body was what made it break. Instead you should use Response.text to get the text

    here is my updated code

    fetch("/validatelogin", {
            method: "POST",
            headers: {'Content-Type': 'application/json'}, 
            body: JSON.stringify({"username": creds[0],"password": creds[1]}, null, 4)
        })
        .then(function (response) {
            return response.text();
        }).then(function (text) {
            console.log(text)
        });
    
    

    and i didn't do anything for the python code


  2. .then(res => res.text).then(data => console.log(data);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search