I am creating a website using HTML, CSS, JS and Python flask but for some reason, when I fetch data from the flask, everything in python works perfect but then the JS does not get the result of the fetch, to be efficient I will just show the JS file and Python code, if you need more ask me for it but I think that should be fine.
const menu = document.querySelector('#mobile-menu');
const menuLinks = document.querySelector('.navbar__menu');
menu.addEventListener('click', function() {
menu.classList.toggle('is-active');
menuLinks.classList.toggle('active');
});
var imgElement = document.getElementById("signUpButton");
imgElement.addEventListener('click', function(){
console.log("Sign Up Image clicked!");
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
console.log({username, email, password});
fetch('http://127.0.0.1:5000/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
email: email,
password: password
})
})
console.log("hey")
.then(response => response.json())
.then(data => {
if (data.success == false){
document.getElementById("resultMessage").innerHTML = "User already exists, please sign in with your account or create a new one";
}
})
.catch((error) => {
console.error('Error', error);
})
});
from flask import Flask, request, jsonify
import json
import os
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "http://localhost:63342"}})
USERS_FILE = os.path.join(os.path.dirname(__file__), 'users.json')
def load_users():
if os.path.exists(USERS_FILE):
with open(USERS_FILE, 'r') as f:
return json.load(f)
return []
def save_users(users):
with open(USERS_FILE, 'w') as f:
json.dump(users, f, indent=4)
@app.route('/signup', methods=['POST'])
def signup():
data = request.get_json()
print("Received data:", data)
username = data['username']
email = data['email']
password = data['password']
users = load_users()
if not username or not email or not password:
print("hi")
return jsonify({"success": False, "message": "Please enter valid username, email, and password."})
elif any(user['username'] == username or user['email'] == email for user in users):
return jsonify({"success": False, "message": "Username or email already exists, please try again!"})
else:
users.append({"username": username, "email": email, "password": password})
print("Updated users list:", users)
save_users(users)
return jsonify({"success": True, "message": "User registered successfully!"})
if __name__ == '__main__':
app.run(debug=True)