未处理的承诺拒绝警告错误

Unhandled Promise Rejection Warning Error

错误

(node:39756) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:561:11) at ServerResponse.header (C:\Users\elegm\OneDrive\Рабочий стол\animflex\api\node_modules\express\lib\response.js:771:10) at ServerResponse.send (C:\Users\elegm\OneDrive\Рабочий стол\animflex\api\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\Users\elegm\OneDrive\Рабочий стол\animflex\api\node_modules\express\lib\response.js:267:15) at C:\Users\elegm\OneDrive\Рабочий стол\animflex\api\routes\auth.js:43:25 at processTicksAndRejections (internal/process/task_queues.js:95:5)

(Use node --trace-warnings ... to show where the warning was created) (node:39756) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:39756) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的代码

router.post("/login", async (req, res) => {
    try {
        const user = await User.findOne({ email: req.body.email });
        if (!user) {
            res.status(401).json("Something went wrong!");
        }
        const bytes = CryptoJS.AES.decrypt(user.password,
            process.env.SECRET_KEY);
        const originalPassword = bytes.toString(CryptoJS.enc.Utf8);

        if (originalPassword !== req.body.password) {
            res.status(401).json("Something went wrong!");
        }

        res.status(200).json(user);
    } catch (err) {
        res.status(500).json(err)
    }
});

module.exports = router;```

原因

Error [ERR_HTTP_HEADERS_SENT] is an interesting error that is fired up when a server tries to send more than one response to a client.

解决方案

router.post("/login", async (req, res) => {
try {
    const user = await User.findOne({ email: req.body.email });
    if(!user){
      res.status(401).json("Something went wrong!");
    } 
    const bytes = CryptoJS.AES.decrypt(user.password, 
process.env.SECRET_KEY);
    const originalPassword = bytes.toString(CryptoJS.enc.Utf8);

    if(originalPassword !== req.body.password) {  
     res.status(401).json("Something went wrong!"); 
     }

    res.status(200).json(user);
} catch (err) {
    res.status(500).json(err)
 }
});

module.exports = router;

这是在 JS 中处理条件的正确方法,在这里你可以阅读更多关于 error