简体   繁体   中英

bcrypt.compare cannot set response headers in nextjs

I can't seem to get the correct response headers when my code enters bcrypt.compare. I thought it was a cors issue at first but I still get the correct response if I entered the wrong and "user does not exist" is displayed.

Here's my api server side code in express

 router.post("/api/signIn", (req, res) => { const { user, password } = req.body; const queryString = "SELECT * FROM users WHERE user_id =?"; db.query(queryString, [user]).then(result => { if (result.length > 0) { const hash = result[0].password; //here bcrypt.compare works server side or with cURL but won't set the response headers in the browser bcrypt.compare(password, hash).then(same => { if (same === true) { console.log("correct password"); res.status(200).json({ code: 200, message: "correct password" }); } else { res.status(401).json({ code: 401, message: "incorrect password" }); } }).catch(err => console.log(err)); } else { //this one works though and i can get the response in the browser so it can't be a cors issue console.log("user does not exist"); res.status(200).json({ code: 401, message: "User does not exist" }); } }).catch(err => { console.log("error" + err.message); }); });

and this is the test function i use in react

 const signIn = () => { fetch("http://localhost:5000/api/signIn", { method: "POST", body: JSON.stringify({ user: userName, password: password }), headers: { "Content-Type": "application/json" }, }).then(res => res.json()).then(response => alert(response.code + response.message)).catch(err => alert(err)); };

so if i entered the wrong username that is not in the database, the alert function would show (code401User does not exist) but if i entered the correct user bcrypt.compare() doesn't seem to set the response for both correct and incorrect passwords and i would get (TypeError: failed to fetch). testing the api in cURL works though.

Got it, I forgot to put event.preventDefault() on the fetch function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM