节点js POST请求错误错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 [英] Node js POST Request error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

查看:616
本文介绍了节点js POST请求错误错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Node JS,Express和Mongo DB开发了REST服务. 我定义了一个POST请求,将用户添加到数据库表中,当我尝试(在本地主机上)通过POSTMAN进行REST服务时,他工作并将用户添加到表中,但是节点应用崩溃(server.js),我收到了此请求错误: 抛出新的ERR_HTTP_HEADERS_SENT('set'); ^

I have developed REST services using Node JS, Express and Mongo DB. I have defined a POST request to add users into DB table, and when I try (on localhost) the REST service by POSTMAN he works and add the user on the table, but the node app crash (server.js) and I receive this error: throw new ERR_HTTP_HEADERS_SENT('set'); ^

错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头 错误是指我的我的我的代码:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client The error is referred to my this my code:

router.post('/user', VerifyToken, function (req, res) {
User.findOne({ username: req.body.username }, function (err, user) {
    if (user) return res.status(400).send({status: 'ko', error: { msg: 'The username you have entered is already associated with another user.'}});

    var hashedPassword = bcrypt.hashSync(req.body.password, 8);
    User.create({
        firstname:req.body.firstname,
        surname:req.body.surname,
        username:req.body.username,
        email: req.body.email,
        password: hashedPassword,
        farmId: req.body.farmId,
        roles: req.body.roles,
        isVerified : req.body.isVerified,
        statusUser : req.body.statusUser
        },
        function (err, user) {
            if (err) return res.status(500).send("There was a problem adding the user to the database.");
            res.status(200).send({status: 'ok', data: { msg: 'User saved', user: user}});

            var client = nodemailer.createTransport(sgTransport(options));

            var email = {
                from: 'noreply-tlcplus@trelleborg.com',
                to: req.body.email,
                subject: 'Registration successfully confirmed',
                text: 'Hi '+ req.body.username + ',\n\nyour account has been registered.\n\nAre you the farm owner?' +
                '\n\nPlease go to this link [CMS link] to create your Profile and start to use the App Plus!\n\n'+
                'If you are a simple user, please just use your credentials to login to the App Plus section into the new App!\n\n'+
                'Download for free from App Store or Google Play!\n\nRegards,\n\nTrelleborg TLC Plus team'
            };

            client.sendMail(email, function(err, json){
                if (err){
                    return res.status(500).send({ msg: err.message });
                }
                else {
                    res.status(200).send({status: 'ok', data: { msg: 'A verification email has been sent to ' + user.email + '.'}} )
                }
            });

        });

});

});

行错误出现在发送验证邮件的res.status(200)上. 为什么我的应用崩溃了,错误在哪里? 请问有什么帮助吗? 谢谢

The line error is on res.status(200) where send the verification mail. Why my app crash, where is the error? Does any help please? Thanks

推荐答案

之所以发生这种情况,是因为您发送了两次响应.因此,错误:

This is happening because you are sending the response twice. Hence, the error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

将您的代码更改为以下内容:

Change your code to the following:

router.post('/user', VerifyToken, function (req, res) {
User.findOne({ username: req.body.username }, function (err, user) {
    if (user) return res.status(400).send({status: 'ko', error: { msg: 'The username you have entered is already associated with another user.'}});

    var hashedPassword = bcrypt.hashSync(req.body.password, 8);
    User.create({
        firstname:req.body.firstname,
        surname:req.body.surname,
        username:req.body.username,
        email: req.body.email,
        password: hashedPassword,
        farmId: req.body.farmId,
        roles: req.body.roles,
        isVerified : req.body.isVerified,
        statusUser : req.body.statusUser
        },
        function (err, user) {
            if (err) return res.status(500).send("There was a problem adding the user to the database.");


            var client = nodemailer.createTransport(sgTransport(options));

            var email = {
                from: 'noreply-tlcplus@trelleborg.com',
                to: req.body.email,
                subject: 'Registration successfully confirmed',
                text: 'Hi '+ req.body.username + ',\n\nyour account has been registered.\n\nAre you the farm owner?' +
                '\n\nPlease go to this link [CMS link] to create your Profile and start to use the App Plus!\n\n'+
                'If you are a simple user, please just use your credentials to login to the App Plus section into the new App!\n\n'+
                'Download for free from App Store or Google Play!\n\nRegards,\n\nTrelleborg TLC Plus team'
            };

            client.sendMail(email, function(err, json){
                if (err){
                    return res.status(500).send({ msg: err.message });
                }

               res.status(200).send({status: 'ok', data: { msg: 'A verification email has been sent to ' + user.email + '.'}, message: 'User saved.'} )

            });

        });

});

});

这篇关于节点js POST请求错误错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆