How do I fix CORS issue in flask with POST request?

Viewed 170

I have the following js function to provide login:

function login(){

    const user = {
        username: document.getElementById("username_id").value,
        password: document.getElementById("pass_id").value
    };
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.crossorigin = true;
    
    xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        console.log(user);
        console.log(this.responseText);
        localStorage.setItem("user", JSON.parse(xhr.responseText).access_token)
    }
    });
    
    xhr.open("POST", "http://127.0.0.1:5000/login");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");


    let data = JSON.stringify(user);
    xhr.send(data);
}

And the following route in flask:

@api_blueprint.route("/login", methods=["POST"])
@cross_origin(support_credentials=True)
def login():
    from app import bcrypt
    data = LoginData().load(request.json)
    if data:
        user = dbu.get_entry_by_username(user_table, username=data["username"])
        hpw = bcrypt.generate_password_hash(data["password"])
        if not user:
            return jsonify({"message": "Couldn't find user!"})
        if bcrypt.check_password_hash(hpw, data["password"]):
            access_token = create_access_token(identity=data["username"], expires_delta=datetime.timedelta(days=365))
            return jsonify(access_token=access_token, id=user.id), 200

Also I have CORS enabled in my flask app:

from flask_cors import CORS
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['CORS_SUPPORTS_CREDENTIALS'] = True

The problem is that when I try to login using js, I have an error in the Console that says The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. and I don't understand where else may I set these credentials to true. I also have two GET requests in my app and they run without any problems. How can I fix it?

0 Answers
Related