const router = require("express").Router();
const user = require("../models/user");
const cryptoJs = require("crypto-js");
const dotenv = require("dotenv").config();
router.post("/register", async (req, res) => {
const newUser = new user({
username: req.body.username,
password: cryptoJs.AES.encrypt(req.body.password, process.env.pass),
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (error) {
res.status(500).json(error);
}
});
router.post("/login", async (req, res) => {
try {
const oneUser = await user.findOne({ username: req.body.username });
if (!oneUser) {
res.status(401).json("Wrong credentials");
}
const hp = cryptoJs.AES.decrypt(oneUser.password, process.env.pass);
const password = hp.toString(cryptoJs.enc.Utf8);
if (password !== req.body.password) {
res.status(401).json("Wrong credentials");
}
res.status(200).json(oneUser);
} catch (error) {
res.sendStatus(500).json(error);
}
});
module.exports = router;
//所以,有代碼!在 /login 部分一切正常。當我輸入正確的用戶名和密碼時,它會從資料庫中獲取匹配的用戶,但是當我立即輸入錯誤的用戶名和正確的密碼時,它會說“錯誤的憑據也可以。但是當我輸入錯誤的密碼時在所有先前的輸入之后,它帶來了這個錯誤“在發送到客戶端后無法設定標題enter code here”
uj5u.com熱心網友回復:
set header error when 將顯示您發送/回傳兩個“res”,因此使用您必須使用 if-else not if
uj5u.com熱心網友回復:
所以問題是您向客戶端發送了回應,而您已經向客戶端發送了回應。當密碼不同時,您發送“錯誤的憑據”,但腳本也會嘗試發送 oneUser Mongo 物件。
要擺脫這種情況,要么使用 if .. else .. 像@Evan 建議的那樣,要么回傳回應,以便您確定腳本停在那里。
“if/else”解決方案
if (password !== req.body.password) {
res.status(401).json("Wrong credentials");
}
else {
res.status(200).json(oneUser); // will be sent if the condition before is not completed
}
“退貨”解決方案
if (password !== req.body.password) {
return res.status(401).json("Wrong credentials"); // if the password is different, this will stop the script here
}
res.status(200).json(oneUser);
uj5u.com熱心網友回復:
你最好改善你的阻塞條件,比如
if (condition){
// do something
}
else {
//do something else
}
或者您可以回傳您的回復。這意味著當您想要發送回應時回傳一些內容并退出函式。您代碼中的此解決方案是
router.post("/register", async (req, res) => {
const newUser = new user({
username: req.body.username,
password: cryptoJs.AES.encrypt(req.body.password, process.env.pass),
});
try {
const savedUser = await newUser.save();
return res.status(201).json(savedUser);
} catch (error) {
return res.status(500).json(error);
}
});
router.post("/login", async (req, res) => {
try {
const oneUser = await user.findOne({ username: req.body.username });
if (!oneUser) {
return res.status(401).json("Wrong credentials");
}
const hp = cryptoJs.AES.decrypt(oneUser.password, process.env.pass);
const password = hp.toString(cryptoJs.enc.Utf8);
if (password !== req.body.password) {
return res.status(401).json("Wrong credentials");
}
return res.status(200).json(oneUser);
} catch (error) {
return res.sendStatus(500).json(error);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/460153.html
