Hello i want to check out if user exist before registration, but of some reason it does't works. something wrong is happening after else. Can some one tell me why? thank you.
//jj. using express
const app = express()
import express, { json } from 'express'
//jj. main array
const allUsers = [{name:"jane"},{name:"jacek"},{name:"morty"}];
//jj. main listener
app.post('/adduser', (req, res) => {
let tocomapre = req.body.name
for (let user of allUsers ){
if(user.name == tocomapre){
console.log(user.name, req.body.name, tocomapre);
console.log('user already exist');
res.status(400).send("User alredy exist")
break
}
else{
try{
const user = {name:req.body.name}
console.log(req.body.name);
allUsers.push(user)
return res.status(200).send('user on board')
}catch{
res.status(500).send(" it's ain't good sthww")
}
}
}
});
======================================================
//jj. request
POST http://localhost:3000/adduser
Content-Type: application/json
{
"name":"morty"
}
You have the else inside the for loop so that a new user is pushed to allUsers if it merely differs from the first existing user. This is wrong.
Replace the break with a return and put the try-catch block after the loop:
let tocomapre = req.body.name
for (let user of allUsers){
if(user.name == tocomapre){
...
return
}
}
try{
...
}catch{
...
}
If the new user is found at any point during the for loop, you issue a 400 error and return. Otherwise you add the user.