[英]When I try to get post data from the MongoDB through postman, I get this cannot set header error
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
”
設置 header 錯誤時會顯示你發送/返回兩個“res”所以使用你必須使用 if-else 而不是 if
所以問題是您向客戶端發送了響應,而您已經向客戶端發送了響應。 當密碼不同時,您發送“錯誤的憑據”,但腳本也會嘗試發送 oneUser Mongo Object。
要擺脫它,要么使用 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);
你最好改善你的街區狀況,比如
if (condition){
// do something
}
else {
//do something else
}
或者您可以回復您的回復。 這意味着當你想發送響應時返回一些東西並從 function 退出。你的代碼中的這個解決方案是
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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.