Sunday 30 September 2018

How to check from frontend if registration was successful in node backend

Hello, I want to check, if user was succesfully registered in node-expess-mongodb. When username is already in db, "status" is changed to false to stop registration and req.session.registrationStatus is set to false, to send info to front end with POST route. If username is unique, user is registered.I have problem, that although it is sort of working, status from req.session.registrationStatus is one step behind real registrationStatus. So registrationStatus is true (but only after second POST connection with db), but I cannnot see where is error. Thank you​Backend:// Route to register user app.post("/register", (req, res, next) => { let username = req.body.content.username; let password = req.body.content.password; let status = true; //status to check if user is already registered db.collection("users") .find() .toArray(function(err, result) { for (let i = 0; i < result.length; i++) { if (result[i].username === username) { console.log("User already registered"); status = false; req.session.registrationStatus = false; //this info is send to frontend req.session.save(); return status = false; } } if (status === true) { bcrypt.hash(password, 10).then(function(hashedPassword) { db.collection("users").insertOne( { username: username, password: hashedPassword }, (err, result) => { if (err) return console.log(err); console.log("saved"); req.session.registrationStatus = true; //this let frontend notify that user was registered req.session.save(); } ); }); } }); }); // Route to check registration app.get("/register/check", (req, res) => { res.send({ registrationStatus: req.session.registrationStatus }); req.session.registrationStatus = false; //registrationStatus is reset to default false value after sending info to frontend req.session.save(); }); Frontend: handleSubmit(event) { post("/register", {username: this.state.username, password: this.state.password}) setTimeout(this.checkRegistration(), 600) event.preventDefault(); } checkRegistration() { const url = "http://localhost:3000/register/check"; fetch(url, { method: "GET", credentials: "include" }) .then(response => response.json()) .then(status => (status.registrationStatus) ? this.setState({ status: "registered." }) : this.setState({ status: "try again." }) ); } Even if user was registered, first response from node is "false" although it should be true.

Submitted September 30, 2018 at 07:06PM by berbebor

No comments:

Post a Comment