繁体   English   中英

为什么我不断收到“错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头”错误?

[英]why do i keep getting 'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client' error?

好的,我对节点 js 相当陌生,我正在学习用户身份验证。 我不断收到“错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头”错误。 有人可以告诉我我的代码有什么问题以及如何解决吗? 当我在 postman 中测试它时,注册路由有效,它的登录路由给了我这个问题。 这是我的代码:

const User = require('../models/User')
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");
const {BadRequestError, UnauthenticatedError} = require('../errors')
const Register = async (req, res)=>{

    const newUser = new User({
        username: req.body.username,
        email: req.body.email,
        password: CryptoJS.AES.encrypt(req.body.password, process.env.pass_secret ).toString(),
    });

    if(newUser){
        const savedUser = await newUser.save();
        res.status(201).json(savedUser);
    }
}


const Login = async (req, res) =>{

    const {username} = req.body

    //checking if both the email and password are provided
    if(!username){
        throw new BadRequestError('please provide a username and password')
    }
    
    //finding a user with the email, if the user doesnt exist, return an error
    const user = await User.findOne({username: req.body.username});
    if(!user){
        throw new UnauthenticatedError('Invalid username or password')
    }

    //checking if the passwords match
    const hashedPassword = CryptoJS.AES.decrypt( user.password, process.env.pass_secret);

    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
    
        
    if(originalPassword !== req.body.password){
        throw new UnauthenticatedError('Invalid email or password')
    } 
    const accessToken = jwt.sign( { id: user._id, isAdmin: user.isAdmin}, process.env.jwt_secret, {expiresIn:"30d"});
  
    const { password, ...others } = user._doc;  
    res.status(200).json({...others, accessToken});
}

module.exports = {Register, Login}

无论你有这个:

if(newUser){
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
}

您需要将其更改为:


if(newUser){
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
    return;
}

您不希望代码在完成后继续

res.status(201).json(savedUser);

因为它会尝试发送另一个响应。

此外,到处都有这个:

if (err) throw err;

在异步回调中,您需要将其替换为实际发送错误响应的内容,例如:

if (err) {
    console.log(err);
    res.sendStatus(500);
    return;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM