节点js POST请求错误错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

时间:2019-08-20 19:05:05

标签: node.js mongodb express

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

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

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)上。 为什么我的应用崩溃了,错误在哪里? 请问有什么帮助吗? 谢谢

2 个答案:

答案 0 :(得分:1)

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

import csv


with open('file.csv', 'rt') as rf:
     reader = csv.reader(rf, delimiter=',')
     for row in reader:
         #print(row[3])    # this works
         usa = "United States"
         if usa in row[3]:
            #print("Its here!)")          #this works too
             repl = row[3].replace("United States", " " )
             # need to write to file- find out how to write changes to a csv file
with open('file.csv', 'w') as wf:
    writer = csv.writer(wf)
    writer.writerows(repl)

rf.close()
wf.close()

将代码更改为以下内容:

First Name,, Last Name,, ID,, Address

答案 1 :(得分:0)

您不能为一个请求发送多个响应。您正在两次发送对请求的响应。创建记录后一个,发送邮件后另一个。创建用户后将其发送并在后台发送电子邮件,或者仅在邮件发送过程完成后才发送成功响应。

希望这会有所帮助:)