简体   繁体   English

当我尝试从 MongoDB 到 postman 获取发布数据时,出现无法设置 header 错误

[英]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;

//so, there is the code. //所以,有代码。 everything works fine up to the /login section, when I input the right username and password, it gets me the matching user from the database, but when I input the wrong username and the right password immediately after.在 /login 部分之前一切正常,当我输入正确的用户名和密码时,它会从数据库中获取匹配的用户,但是当我输入错误的用户名和正确的密码后立即。 it says "wrong credentials which is also fine, But when I input the wrong password after all the previous inputs, it brings this error " Cannot set headers after they are sent to the client enter code here "它说“错误的凭据也很好,但是当我在之前的所有输入之后输入错误的密码时,它会带来这个错误“将标题发送到客户端后无法设置标题在enter code here

The set header error when will display that you send/return two "res" so use you have to use if-else not if设置 header 错误时会显示你发送/返回两个“res”所以使用你必须使用 if-else 而不是 if

So the problem is that you send a response to the client, while you already sent a response to the client.所以问题是您向客户端发送了响应,而您已经向客户端发送了响应。 When the password is different, you send "Wrong Credentials", but the script will also try to send the oneUser Mongo Object.当密码不同时,您发送“错误的凭据”,但脚本也会尝试发送 oneUser Mongo Object。

To get rid of that, either use an if.. else.. like @Evan proposed, either return the response so you're sure that the script stop there.要摆脱它,要么使用 if..else.. 就像@Evan 提议的那样,要么返回响应,这样你就可以确定脚本停在那里。

The "if/else" solution “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
}

The "return" solution “回归”解决方案

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);

its better you improve youre block condition like你最好改善你的街区状况,比如

if (condition){
// do something 
}
else {
//do something else
}

OR you can return youre response.或者您可以回复您的回复。 it means that when you want to send response return something and exit from the function. this solution in your code is这意味着当你想发送响应时返回一些东西并从 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.

相关问题 当我尝试连接到 mongodb 时出现此错误 - when i try to connect to mongodb get this error 我正在尝试使用以下代码通过 postman 将一些数据发布到 mongo compass atlas 但收到此错误 - I'm trying to post some data through postman into mongo compass atlas using the following code but get this error 在MongoDB find函数中,我回调并使用res.redirect,我得到一个无法设置的头错误? - Inside a MongoDB find function, I callback and use a res.redirect, I get a cannot set header error? 当我尝试连接到 mongodb 时出现此错误 - I get this error when i try to connect to mongodb 由CURL发送的发布请求被正确解析,但是从邮递员发送时,我得到未定义的数据 - Post request sent by CURL gets parsed correctly but when sent from postman, I get undefined data 如何在 Nodejs Mongodb 中设置最低价格最高价格参数,并从通过 postman 发布的这些查询中获取数据 - How to set min price max price parameters in Nodejs Mongodb, and get data from these queries posted through postman 当我尝试将数据传递到节点中的响应时,我得到:“错误”:{“消息”:“无法读取未定义的属性'length'”, - When I try to pass data to a response in Node I get: “error”:{“message”:“Cannot read property 'length' of undefined”, 为什么在尝试发送带有标题的请求时出现错误? - Why i get error when try post request with headers? 当我尝试从“/api/products”获取数据时,为什么会出错? - Why do I get an error when I try to get data from “/api/products”? 当我尝试通过 node.js 从 mongodb 获取数据时出现问题? - There is some issue when I try to get data from mongodb by node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM