You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js报错Cannot set headers after they are sent to the client求助

解决Express中"Cannot set headers after they are sent to the client"错误

你的代码存在三个核心问题,导致了这个错误:

  1. 响应发送后未终止代码执行
    你用!user && res.status(401).json(...)这种写法发送错误响应后,函数并没有停止执行,后续代码还会继续运行,尝试再次发送响应,这就触发了"重复设置响应头"的错误。必须在发送错误响应后用return终止函数。

  2. 错误使用response对象
    你引入了Express的response构造函数,但当前请求的响应对象是res,使用response.status(200).json(user)会导致异常,应该替换为res。

  3. 加密/解密环境变量不一致
    注册路由用process.env.SEC_KEY加密密码,登录路由却用process.env.SECRET_KEY解密,这会导致密码解密失败,需要保持环境变量名一致。

修复后的完整代码:

const router = require('express').Router();
const User = require('../models/user');
const Crypto = require('crypto-js');
// 不需要单独引入response,直接用req,res参数即可
const secretKey = process.env.SEC_KEY; // 统一使用SEC_KEY

// 注册路由
router.post('/rejestracja', async (req, res)=>{
    const nowyUser = new User({
        email: req.body.email,
        password: Crypto.AES.encrypt(req.body.password, process.env.SEC_KEY).toString(),
        firstName: req.body.firstName,
        surname: req.body.surname,
        username: req.body.username,
    });
    try{
        const newedUser = await nowyUser.save();
        res.status(201).json(newedUser);
    }
    catch(err){
        res.status(500).json(err);
    };
})
 
// 登录路由
router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne({email: req.body.email});
        if(!user) {
            return res.status(401).json("Email i/lub hasło jest nieprawidłowy");
        }

        const securedPass = Crypto.AES.decrypt(user.password, process.env.SEC_KEY);
        const password = securedPass.toString(Crypto.enc.Utf8);
        
        if(password !== req.body.password) {
            return res.status(401).json("Email i/lub hasło jest nieprawidłowy");
        }
        
        res.status(200).json(user);
        console.log("dziala");
    } 
    catch(err) {
        res.status(500).json({message: err.message});
    }
});

module.exports = router

另外,确保你的.env文件里正确配置了SEC_KEY变量,并且用dotenv包加载了环境变量(如果还没安装,执行npm install dotenv,然后在项目入口文件添加require('dotenv').config())。

内容的提问来源于stack exchange,提问作者Z3eme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:15:37